测试方法命名
- 简单测试:以test开头,以业务方法结尾。如业务方法名:isToday,测试方法可命名为:testIsToday;
- 复杂测试:期望结果_测试场景。
测试方法声明
必须是public修饰的,必须没有返回值,必须没有参数,必须使用@Test注解修饰。
运行测试方法
-
选中测试方法名 -->右键--> Run '测试方法名' 运行选中测试方法;
-
选中类名 -->右键 -->Run '测试类名' 运行选中类所有的测试方法;
-
选中模块名 -->右键 -->Run 'All Tests' 运行选中模块中所有测试类中的所有测试方法。
测试结果
- 绿色:代表测试成功,没有问题
- 红色:代表测试出现问题
注解
- @Before:在每一个测试方法执行之前执行一次
- @After:会在每一个测试方法执行之后执行一次
- @BeforeClass:在所有测试方法执行之前执行一次,全局只会执行一次,且是第一个运行
- @AfterClass: 在所有测试方法执行之后执行一次,全局只会执行一次,且是最后一个运行
-
@Test:测试方法
-
@Ignore 忽略此方法
断言方法 
class AssertionsTest {
@Test
fun testAssertNull() {
val str: String? = null
assertNull(str)
}
@Test
fun testAssertNotNull() {
val str = "hello Java!!"
assertNotNull(str)
}
@Test
fun testAssertEqualsLong() {
val long1: Long = 2
val long2: Long = 2
assertEquals(long1, long2)
}
@Test
fun testAssertEqualsDouble() {
// test case is successful as double1 and double 2
// differ by 0.001 which is less than our specified delta
val double1 = 1.236
val double2 = 1.237
val delta = 0.002
assertEquals(double1, double2, delta)
}
@Test
fun testAssertTrue() {
val list: List<String> = ArrayList()
assertTrue(list.isEmpty())
}
@Test
fun testAssertFalse() {
val list: MutableList<String> = ArrayList()
list.add("hello")
assertFalse(list.isEmpty())
}
@Test
fun testAssertSame() {
val str1 = "hello world!!"
val str2 = "hello world!!"
assertSame(str2, str1)
}
@Test
fun testAssertNotSame() {
val str1 = "hello world!!"
val str3 = "hello Java!!"
assertNotSame(str1, str3)
}
}