参见:
https://segmentfault.com/a/1190000004229002
一、单元测试
单元测试框架这里介绍两种: JUnit 和 Robolectric。
JUnit:
JUnit是java领域应用非常普及,使用简单,但只能测试逻辑代码,针对和Android SDK相关的代码会报相应的错误。
- 使用:
1)编写测试之前,需要为其新建一个目录,通常较test,他会和你的main文件夹平级。
2)建议你使用JUnit 4,你可以将其作为依赖添加到你的依赖库。
dependencies {
testCompile 'junit:junit:4.12'
}
如果你有其他的构建版本呢,而你又只是想为特定版本添加该jar,你只需要这么做:
dependencies {
testPaidCompile ‘junit:junit:4.12’
}
3)当所有的事情都OK了,就是时候开始写测试代码了。下面是简单的测试代码:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class LogicTest {
@Test
public void addingNegativeNumberShouldSubtract() {
Logic logic = new Logic();
assertEquals("6 + -2 must be 4", 4, logic.add(6, -2));
assertEquals("2 + -5 must be -3", -3, logic.add(2, -5));
}
}
4)单个测试用例导致整个测试失败,这样不好,如果你想把整个测试案例都跑一遍,那也很简单啊:
$ gradlew test –continue
而且其还会为你创建一份测试报告,你可以找到它app/build/reports/tests/debug/index.html
Robolectric的使用大致也类似,有兴趣移步上面链接阅读。