[android] android下junit测试框架配置

我们的业务代码一般是放在一个新的包下面,这个业务类不能够通过右键run as java application,因为android项目只能运行在手机上的dalvak虚拟机里面

 

新建一个包,里面写测试类,测试类需要继承AndroidTestCase类,写测试方法,需要throws exception抛出异常给测试框架,测试方法里面一般new出需测试的类,调用它的方法,然后断言结果,assertEquals(预估实际结果)

 

outline视窗 (window=>show view=>outline)里面选中该方法右键run as android junit test

此时会报错

[2016-02-27 21:29:54 - 单元测试单元测试 does not specify a android.test.InstrumentationTestRunner instrumentation or does not declare uses-library android.test.runner in its AndroidManifest.xml

需要在清单文件里面配置instrumentation指令集

    <!-- 指令集在manifest节点下 -->

    <!-- 测试用例,名称是固定的,目标包名 -->

    <instrumentation

        android:name="android.test.InstrumentationTestRunner"

        android:targetPackage="com.tsh.junit" >

</instrumentation>

            <!-- 使用的函数库,在application节点下 -->

        <uses-library android:name="android.test.runner"/>

Xml里面写注释 ctrl+shift+/

 

Junit里面打印出绿条,说明没有错误,如果有错误打印红色的条,错误追逐里面有错误信息,如断言错误等,如果清单文件里面的信息记不住,那么请这样操作,new => project =>android android test project => select test target 完成以后会有个项目里面有清单文件 

 

java代码:

 

复制代码
package com.tsh.junit.test;

import com.tsh.junit.service.CalcService;

import android.test.AndroidTestCase;

public class CalServiceTest extends AndroidTestCase {
    public void testAdd() throws Exception{
        CalcService service=new CalcService();
        int res=service.add(3, 5);
        assertEquals(8, res);
    }
}
复制代码

 

清单文件:

复制代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tsh.junit"
    android:versionCode="1"
    android:versionName="1.0" >
    <!-- 指令集在manifest节点下 -->
    <!-- 测试用例,名称是固定的,目标包名 -->
    <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="com.tsh.junit" >
    </instrumentation>

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="23" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <!-- 使用的函数库,在application节点下 -->
        <uses-library android:name="android.test.runner"/>
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
复制代码

 

posted @   唯一客服系统开发笔记  阅读(394)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示
1
chat with us