JUnit3、JUnit4 JUnit5
写这篇文章的时候JUnit5正式版刚刚发布不久。
1,每一个测试类都需要继承自TestCase
2,每一个测试方法都要以测试开头
3,初始化方法名必须是:设置
4,释放资源的方法么必须是:拆卸
1,初始化方法使用@Before或@BeforeClass标识
2,释放资源方法名用@After或@AfterClass标识
3,命名无限制,为了兼容,JUnit4通常沿用了JUnit3的命名规则(非必须)
备注:
,,,在使用AWS设备农场早期版本时,带有测试的类才会被识别为测试类,带有测试的方法才会被识别为测试方法。对于带有@Test注解而没有以测试开头的方法是不会被识别为测试方法的。可能是业界的默认做法或者说版本支持的混乱,所以沿用JUnit3的命名规则有可能省去不必要的麻烦。
MethodSorters。name_ascending
,,,根据方法名升序排列,结合方法001002名的规则,唯一稳定的方式
MethodSorters。jvm
,,,根据JVM返回的顺序,每次执行可能不同
MethodSorters。默认的
,,,根据方法名的HashCode排序,而HashCode计算规则在不同机器上可能不同
备注:
,,,JUnit强调用例之间的独立性,彼此之间不具有依赖性。如果要更精准控制用例之间的依赖,可以改用TestNG的依赖测试。
@Test(超时=2000)
用例需要在2秒钟之内执行完毕,否则测试失败
@Test(预期=ArithmeticException.class)
用例需要抛出指定异常,否则执行失败
一次执行多个测试类
@RunWith (Suite.class) @Suite.SuiteClasses ({JunitOne.class, JunitTwo.class}) public class  TestSuite {,}//根据列出来的测试类,依次执行,TestSuite测试类内容为空。
<强>注解使用范例:强>
@FixMethodOrder (MethodSorters.NAME_ASCENDING) public class  JunitTest { ,,@BeforeClass ,,,public static void testBeforeClass () { ,,,,,,,System.out.println (“BeforeClass”); ,,,} ,,@AfterClass ,,,public static void testAfterClass () { ,,,,,,,System.out.println (“AfterClass”); ,,,} ,,@Before ,,,public void testBefore () { ,,,,,,,System.out.println(“之前”); ,,,} ,,@After ,,,public void testAfter () { ,,,,,,,System.out.println(“后”); ,,,} ,,,@ ignore (“not ready for 测试”) ,,@Test ,,,public void test002 () { ,,,,,,,System.out.println (“test002”); ,,,} ,,,@Test (=expected ArithmeticException.class) ,,,public void test003 () { ,,,,,,,System.out.println (“test003”); ,,,,,,,int result =, 3,/, 0; ,,,} ,,,@Test (timeout =, 2000) ,,,public void test001 (), throws 异常{ ,,,,,,,thread . sleep (1900); ,,,,,,,System.out.println (“test001”); ,,,} ,,,@Test (=timeout 1000年,expected =, ArrayIndexOutOfBoundsException.class) ,,,public void test004 () { ,,,,,,,System.out.println (“test004”); ,,,,,,,int [], array =, new int [3]; ,,,,,,,int a =,数组[3]; ,,,} } 测试结果: BeforeClass 之前 test001 后 not ready  for 测试 之前 test003 后 之前 test004 后 AfterClass
备注:
,,,其中test001到test004会按照名称降序执行,test002会被忽略.test003要求用例抛出ArithmeticException异常.test001要求用例在2000毫秒以内执行完毕,test004则同时限制了执行时长以及指明需要抛出的异常类。
@RunWith (Parameterized.class) public class  NewTest { ,,,private String 名称; ,,,private int 年龄; ,,,, ,,,public 纽特(String ,, int b) { ,,,,,,,this.name =,, ,,,,,,,this.age =, b; ,,,} ,,,, ,,,@Parameterized.Parameters ,,,public static List 添加(){ null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null nullJUnit4使用总结及维护