在项目中创建单元测试时junit的配置和使用

时间:2023-03-09 14:38:52
在项目中创建单元测试时junit的配置和使用

首先配置项目中AndroidMainfest.xml文件,加入

<instrumentation
       android:name="android.test.InstrumentationTestRunner"
       android:targetPackage="com.example.filecontrol" />

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

需要注意的是两处代码位置不要放错,而且前者当中的包名android:targetPackage="com.example.filecontrol

需要与AndroidMainfest.xml原有的package="com.example.filecontrol"匹配,代表你要测试的单元应用,添加后AndroidMainfest.xml如图所示

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.filecontrol"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <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>

    <instrumentation
       android:name="android.test.InstrumentationTestRunner"
       android:targetPackage="com.example.filecontrol" />

</manifest>

配置完成后新建测试类filetest继承AndroidTestCase,测试对象为fileService类中的一个读文件操作即read()方法,并打印返回值,如图

在项目中创建单元测试时junit的配置和使用

测试正确的话会得到如图结果,绿色代表正确,LogCat中可看到读到的数据为123456

在项目中创建单元测试时junit的配置和使用