Android中使用自身携带的Junit新建一个测试工程

本文介绍了一个简单的 Android JUnit 测试案例,包括如何创建一个 Android 工程,并进行单元测试。文中提供了 Service 类及对应的测试类 Test 的代码实现,展示了基本的除法运算及其测试方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、新建立一个Android工程

复制代码
package com.shellway.junit;

public class Service {
      public int divide(int a,int b){
          return a/b;
      }
}
复制代码
复制代码
package com.shellway.junit;

import junit.framework.Assert;
import android.test.AndroidTestCase;

public class TestT extends AndroidTestCase {
    public void test1(){
        Service service = new Service();
        System.out.println(service.divide(10, 2));
    }
    public void test2(){
        Service service = new Service();
        System.out.println(service.divide(10, 0));
    }
    public void test3(){
        Service service = new Service();
        Assert.assertEquals(2.5, service.divide(10, 4));
    }
}
复制代码
复制代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shellway.junit"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="21" />
       <instrumentation
        android:targetPackage="com.shellway.junit"
        android:name="android.test.InstrumentationTestRunner" />
    
    <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>
</manifest>
复制代码

注意:在配置文件中要加入的内容是:

 <instrumentation
      android:targetPackage="com.shellway.junit"
      android:name="android.test.InstrumentationTestRunner" />

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

并且要注意他们加入的位置。这是一种测试自身工程的方法。

另一种方法是:新建一个Android Junit工程来测试另外的一个工程,这里需要注意的是建立这个测试工程名的时候不能以Test来命名,不然出现错误都很难找出问题所在,下面给出以Test来命名工程的出错信息。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值