我想知道如何使用 android sdk 中包含的(基于 JUnit 的)测试框架在不使用任何 android SDK 代码的 Android 项目中测试一个简单的 Java 类。 或者我是否必须使用外部 (JUnit) 测试库? 问候。
最佳答案
谢谢大家,我通过这个链接得到了线索 https://marakana.com/tutorials/android/junit-test-example.html , 但我不得不稍微调整一下以满足我的需要。
因此,如果要使用 android 测试框架为 android 项目中的一个简单类编写测试,比如计算器类。
package com.example.application;
public class Calculator {
public static int add(int a, int b){
return a+b;
}
public static int sub(int a, int b){
return a-b;
}
}
您必须在测试项目中创建以下测试类:
package com.example.application.tests;
import android.test.AndroidTestCase;
import com.example.application.Calculator;
public class CalculatorTest{
public void testAdd() throws Throwable{
assertEquals(3, Calculator.add(1,2);
}
public void testSub() throws Throwable{
assertEquals(-1, Calculator.add(1,2);
}
}
并且在命令行下,编译安装主工程和测试工程后,在模拟器上(以实例为例),可以使用如下命令来测试该类:
adb shell am instrument -w -e class com.example.appplication.tests.CalculatorTest com.example.application.tests/android.test.InstrumentationTestRunner
您还可以使用 Eclipse 来运行测试。
希望这会对某人有所帮助。
关于android - 使用 Android SDK 进行简单的 Java 类测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18213849/