一.JUnit的使用
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
仅支持纯Java代码,直接运行就是一次单元测试
二.JUnit注解
@Test
说明该方法是测试方法。测试方法必须是public void,可以抛出异常。
@Before
它会在每个测试方法执行前都调用一次。
@After
与@Before对应,它会在每个测试方法执行完后都调用一次。
@BeforeClass
它会在所有的测试方法执行之前调用一次。与@Before的差别是:@Before注解的方法在每个方法执行前都会调用一次,有多少个测试方法就会掉用多少次;而@BeforeClass注解的方法只会执行一次,在所有的测试方法执行前调用一次。注意该注解的测试方法必须是public static void修饰的。
@AfterClass
与@BeforeClass对应,它会在所有的测试方法执行完成后调用一次。注意该注解的测试方法必须是public static void修饰的。
@Ignore
忽略该测试方法,有时我们不想运行某个测试方法时,可以加上该注解
三.常用断言
assertEquals([message], expected, actual)
验证期望值与实际值是否相等,如果相等则表示测试通过,不相等则表示测试未通过,并抛出异常AssertionError。message表示自定义错误信息,为可选参数,以下均雷同。
assertNotEquals([message], unexpected, actual)
验证期望值与实际值不相等。
assertArrayEquals([message], expecteds, actuals)
验证两个数组是否相同
assertSame([message], expected, actual)
断言两个引用指向同一个对象。
assertNotSame([message], expected, actual)
断言两个引用指向不同的对象。
assertNull([message], object)
断言某个对象为null。
assertNotNull([message], object)
断言对象不为null。
assertTrue([message], condition)
断言条件为真。
assertFalse([message], condition)
断言条件为假
四.@RunWith和Suite
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestLogin.class,
TestLogout.class,
TestUpdate.class
})
public class TestSuite {
//不需要有任何实现方法
}
@RunWith指定测试的引擎,@Suite是一起执行测试方法
@RunWith(Suite.class)
@Suite.SuiteClasses(TestSuite.class)
public class TestSuite2 {
}
五.Parameterized
//指定Parameterized作为test runner
@RunWith(Parameterized.class)
public class TestParams {
//这里是配置参数的数据源,该方法必须是public static修饰的,且必须返回一个可迭代的数组或者集合
//JUnit会自动迭代该数据源,自动为参数赋值,所需参数以及参数赋值顺序由构造器决定。
@Parameterized.Parameters
public static List getParams() {
return Arrays.asList(new Integer[][]{
{ 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 }
});
}
private int input;
private int expected;
//在构造函数里,指定了2个输入参数,JUnit会在迭代数据源的时候,自动传入这2个参数。
//例如:当获取到数据源的第3条数据{2,1}时,input=2,expected=1
public TestParams(int input, int expected) {
this.input = input;
this.expected = expected;
}
@Test
public void testFibonacci() {
System.out.println(input + "," + expected);
Assert.assertEquals(expected, Fibonacci.compute(input));
}
}
本文详细介绍了JUnit的基本使用,包括测试注解、断言方法及参数化测试。通过实例演示了如何编写单元测试,如使用@Test注解标记测试方法,@Before和@After注解设置测试前后置操作,以及@RunWith和@Suite整合多个测试类。
848

被折叠的 条评论
为什么被折叠?



