Junit 4 单元测试常规内容简介

对代码测试的正确理解:

测试用例用来达到想要的预期结果,可是对于逻辑错误无能为力;测试用例不是用来证实你是对的,而是用来证实你是没错的。java

注意以及建议事项:数据库

一、测试方法上必须使用@Test进行修饰。api

二、测试方法必须使用public void进行修饰,不能带任何的参数。异步

三、尽可能将测试类放在一个单独的源代码目录中,尽可能不要放在源程序文件目录(仅仅是我的建议)。ide

四、测试类的包应该和被测试类保持一致。函数

五、测试单元中的每一个方法必须能够独立测试,测试方法间不能有任何依赖。单元测试

测试过程当中常见错误测试

一、Failure通常由单元测试使用的断言方法判断失败所引发的,这表示测试点发现了问题,就是说程序输出的结果和咱们预期的结果不同。ui

二、Error是由代码异常引发的,它能够产生于测试代码自己的错误,也能够是被测试代码中的一个隐藏bug。this

Junit运行流程以及常见注解:

一、@BeforeAll / BeforeClass:修饰的方法会在全部方法被调用前执行,而且该方法是静态的,因此当测试类被加载后接着运行。

二、@AfterAll / AfterClass:修饰的方式一般用来对资源的清理,如关闭数据库的链接。

三、@BeforeEach / Before:会在每一个测试方法执行前执行一次。

四、@AfterEach / After:会在每一个测试方法执行后执行一次。

五、@Ignore:所修饰的测试方法会被测试运行器忽略

六、@RunWith:能够更改测试运行器 org.junit.runner.Runner

七、@RunWith(Suite.class):声明套件运行器,若是是须要多个单元测试类整合测试 使用一个Runner进行异步测试,只须要把相关的class放入到SuiteClasses{}中便可

八、参数化设置:须要测试的仅仅是测试数据,代码结构是不变的,只须要更改测试数据。

具体步骤:(1)、更改默认的测试运行器为@RunWith(Parameterized.class)。

(2)、声明变量来存放预期值和测试值。

(3)、声明一个返回值为Collection的公共静态方法,并用@Parameters修饰。

(4)、为测试类声明一个带有参数的公共构造函数,并在其中为他声明变量赋值。

package com.CalculateTest;

import static org.junit.jupiter.api.Assertions.*;

import java.util.Arrays;
import java.util.Collection;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

import com.Calculate.Calculate;

@RunWith(Parameterized.class)

public class ParameteriTest {
	
	int expected = 0;;
	int input1 = 0;
	int input2 = 0;
	
	@Parameters
	public static Collection<Object[]> t(){
		
		return Arrays.asList(new Object[][] {
				{3,1,2},
				{4,2,2}
		});
	}
	
	public ParameteriTest(int expected, int input1, int input2) {
		// TODO Auto-generated constructor stub
		
		this.expected = expected;
		this.input1 = input1;
		this.input2 = input2;
	}

	@Test
	public void testAdd() {
		fail("Not yet implemented");
		
		assertEquals(expected, new Calculate().add(input1, input2));
	}

}

九、@Test(expected=XX.class)捕获抛出异常

十、@Test(timeout=XX毫秒)限制方法的运行时效