JUnit4笔记三——JUnit详解之运行流程及常用注解

604 阅读3分钟

这篇笔记记录JUnit测试类运行时,类中方法的运行顺序;以及JUnit中常用的注解。

1.JUnit的运行流程

1.1 新建测试类

右键被测试类,新建一个测试类。弹出框中,首先改变测试类所在的代码目录,然后勾选4个方法:
在这里插入图片描述

1.2 修改测试类代码

package com.fzhiy.junit02;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * 
 * @author yufeng
 */
public class JunitFlowTest {

	/**
	 * @throws java.lang.Exception
	 */
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		System.out.println("this is setUpBeforeClass()...");
	}

	/**
	 * @throws java.lang.Exception
	 */
	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		System.out.println("this is tearDownAfterClass()...");
	}

	/**
	 * @throws java.lang.Exception
	 */
	@Before
	public void setUp() throws Exception {
		System.out.println("this is setUp()...");
	}

	/**
	 * @throws java.lang.Exception
	 */
	@After
	public void tearDown() throws Exception {
		System.out.println("this is tearDown()...");
	}

	@Test
	public void test() {
		System.out.println("this is test()...");
	}

}

运行结果:
在这里插入图片描述
在测试类中,增加一个test2()测试方法:

@Test
public void test2(){
	System.out.println("this is test2()...");
}

再次运行,结果如下:
在这里插入图片描述

1.3 总结说明

​ 1)BeforeClass修饰的方法会在所有方法被调用前被执行,而且该方法是静态的,所以当测试类被加载后接着就会运行它,而且在内存中它只会存在一份实例,它比较适合加载配置文件,进行初始化等等
​ 2)@AfterClass所修饰的方法会在所有方法被调用后被执行,通常用来对资源的清理,如关闭数据库的连接

​ 3)@Before和@After会在每个测试方法的前后各执行一次。

2.JUnit常用注解

​ @Test:将一个普通的方法修饰成为一个测试方法
​ @Test(expected=XX.class)
​ @Test(timeout=毫秒)
​ @BeforeClass:它会在所有的方法运行前被执行,static修饰
​ @AfterClass:它会在所有的方法运行结束后被执行,static修饰
​ @Before:会在每一个测试方法被运行前执行一次
​ @After:会在每一个测试方法运行后被执行一次
​ @Ignore:所修饰的测试方法会被测试运行器忽略
​ @RunWith:可以更改测试运行器 org.junit.runner.Runner

2.1 @Test、@Ignore的测试

例子代码:

package com.fzhiy.junit02;

import static org.junit.Assert.assertEquals;

import org.junit.Ignore;
import org.junit.Test;

/**
 * 
 * @author yufeng
 */
public class AnotationTest {

	@Test(expected=ArithmeticException.class)
	public void testDivide() {
		assertEquals("除法有问题",3, new Calculate().divide(6, 0)); //将除数设置为0
	}
	
	@Test(timeout=2000)
	public void testWhile() {
		while(true) {
			System.out.println("run forever...");  //一个死循环
		}
	}
	
	@Test(timeout=3000)
	public void testReadFile(){
		try {
			Thread.sleep(2000);       //模拟读文件操作
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	@Ignore("...")
	@Test
	public void testIgnore() {
		System.out.println("会运行吗?");  
	}
}

输出结果:
在这里插入图片描述
在这里插入图片描述
说明:
①testDivide()方法中,将除数设为0,本会抛出Error,但设置了@Test(expected=ArithmeticException.class),说明我们预期它会抛出一个算术异常,所以程序结果也符合我们的预期。
②testWhile()方法是一个死循环,但设置了@Test(timeout=2000),即2秒之后,自动结束循环
③testReadFile()方法模拟读取文件操作,设置读取超时时间为3秒,等于或大于测试时间则认为不成功,而程序睡眠了2秒,没有超时。这里表示用作一些性能的测试。

​ ④testIgnore()方法,因为使用的@Ignore注解,所以不会运行。

2.2 @RunWith

当类被@RunWith注解修饰,或者类继承了一个被该注解修饰的类,JUnit将会使用这个注解所指明的运行器(runner)来运行测试,而不是JUnit默认的运行器。