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

版权声明:最终解释权归属Hern所有,恒! https://blog.csdn.net/qq_36761831/article/details/85219161

对代码测试的正确理解:

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

注意以及建议事项:

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

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

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

4、测试类的包应该和被测试类保持一致。

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

测试过程中常见错误

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

2、Error是由代码异常引起的,它可以产生于测试代码本身的错误,也可以是被测试代码中的一个隐藏bug。

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

1、@BeforeAll / BeforeClass:修饰的方法会在所有方法被调用前执行,并且该方法是静态的,所以当测试类被加载后接着运行。

2、@AfterAll / AfterClass:修饰的方式通常用来对资源的清理,如关闭数据库的连接。

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

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

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

6、@RunWith:可以更改测试运行器 org.junit.runner.Runner

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

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

具体步骤:(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));
	}

}

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

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

猜你喜欢

转载自blog.csdn.net/qq_36761831/article/details/85219161