1.@BeforeClass 测试类最开始执行的方法,并且只执行一次
2.@AfterClass 测试类最后执行的方法,并且只执行一次
3.@Before 每个测试方法都会在执行之前调用一次的方法
4.@After 每个测试方法都会在执行之后调用一次的方法
以上四个注解修饰的方法均需要抛出Exception异常
5.@Ignore 暂时不执行的测试,下面这个方法在测试类执行时不会被调用
6.@Test 普通测试
7.@Test(timeout=long) 超时测试
8.@Test(expected=Exception) 预期异常的测试,该注解修饰的方法抛出预期的异常则为正确的,反之则会报Errors
断言方法:junit4提供了多个方法名为assertEquals的重载方法,查api即可。
下面提供示例程序:
被测试的类为Main,测试类为MainTest
package com.jison; /** * 被测试的类 * @author jison * */ public class Main { /** * 计算n的阶乘 * @param n * @return */ public int factorial(int n){ int factorialNum = 1; for (int i = 1; i < n+1; i++) { factorialNum = factorialNum * i; } return factorialNum; } /** * 计算n的阶乘 * @param n * @param type 值为false时让程序报空指针 * @return * @throws Exception */ public int factorial(int n, boolean type) throws NullPointerException{ if(!type){ throw new NullPointerException(){}; } return factorial(n); } }
package junit4; import static org.junit.Assert.assertEquals; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import com.jison.Main; /** * 测试类 * @author jison * */ public class MainTest { /** * 测试类最开始执行的方法,并且只执行一次 * @throws Exception */ @BeforeClass public static void setUpBeforeClass() throws Exception { System.out.println("setUpbeforeClass"); } /** * 测试类最后执行的方法,并且只执行一次 * @throws Exception */ @AfterClass public static void tearDownAfterClass() throws Exception { System.out.println("tearDownAfterClass"); } /** * 每个测试方法都会在执行之前调用一次的方法 */ @Before public void setUp() throws Exception { System.out.println("setUp"); } /** * 每个测试方法都会在执行之后调用一次的方法 * @throws Exception */ @After public void tearDown() throws Exception { System.out.println("tearDown"); } /** * 普通测试 */ @Test public void testFactorial() { // 断言方法 assertEquals(120, new Main().factorial(5)); } /** * 超时测试 * 会报Errors */ @Test(timeout=1) public void testFactorial2(){ // 通过循环Long类型的最大值模拟超时的程序 for (int i = 0; i < Long.MAX_VALUE; i++) {} assertEquals(3628800, new Main().factorial(10)); } /** * 测试到预期的异常 */ @Test(expected=NullPointerException.class) public void testFactorial3() throws NullPointerException{ // 参数true不报异常,false报异常 assertEquals(120, new Main().factorial(5, false)); } /** * 没有测试到预期的异常,报Failures */ @Test(expected=NullPointerException.class) public void testFactorial31() throws NullPointerException{ // 参数true不报异常,false报异常 assertEquals(120, new Main().factorial(5, true)); } /** * 本应该通过测试到预期的异常,但是catch处理后则报Failures */ @Test(expected=NullPointerException.class) public void testFactorial32(){ // 参数true不报异常,false报异常 try{ assertEquals(120, new Main().factorial(5, false)); } catch(NullPointerException e){ System.out.println("以下是预期的异常信息:"); e.printStackTrace(); } } /** * 暂时不执行的测试 * 下面这个方法在测试类执行时不会被调用 */ @Ignore public void testFactorial4(){ System.out.println("Ignore"); } }