0%
常规的单元测试
编写被测试类
进行单元测试首先需要一个被测试类和被测试方法
1 2 3 4 5
| public class Div{ public static void div(int a, int b){ return a/b; } }
|
编写测试类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class DivTest { @BeforeClass public static void initClass(){ System.out.println("加载类前执行"); } @Before public void init(){ System.out.println("执行每个方法前执行"); }
@Test public void divTest(){ TestCase.assertEquals(3, Div.div(6,2)); System.out.println("预期值为3,实际值为3"); } @After public void destory(){ System.out.println("执行每个方法后执行"); }
@AfterClass public static void destoryClass(){ System.out.println("执行完所有Test方法后执行"); } }
|
其他常用注释
@Test
expected
:预期会抛出某个异常
timeout
:预期运行时间不超过xx
毫秒
1 2 3 4 5 6 7
| public class DivTest { @Test(expected = ArithmeticException.class, timeout = 2000) public void divTest(){ TestCase.assertEquals(3, Div.div(6,0)); } }
|
@Ignore
1 2 3 4 5 6 7 8
| public class DivTest { @Ignore @Test() public void divTest(){ TestCase.assertEquals(3, Div.div(6,0)); } }
|
测试套件的使用(多个测试类一起执行)
有时候需要将几个测试类一起测试,需要用到测试套件
1 2 3 4 5
| @RunWith(Suite.class) @Suite.SuiteClasses({DivTest.class,DivTest.class}) public class SuiteTest { }
|
参数化设置(编写测试用例)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| @RunWith(Parameterized.class) public class ParameterizdTest { int expected = 0; int input1 = 0; int input2 = 0; public ParameterizdTest(int expected, int input1, int input2){ this.expected = expected; this.input1 = input1; this.input2 = input2; }
@Parameterized.Parameters public static Collection<Object[]> t(){ return Arrays.asList(new Object[][]{ {3, 6, 2}, {4, 4, 2} }); }
@Test public void divTest(){ TestCase.assertEquals(expected, Div.div(input1, input2)); } }
|