JUnit基本用法

JUnit的一些注意事项:

  • 测试方法必须使用@Test修饰
  • 测试方法必须使用public void进行修饰,不能带参数
  • 一般使用单元测试会新建一个test目录存放测试代码,在生产部署的时候只需要将test目录下代码删除即可
  • 测试代码的包应该和被测试代码包结构保持一致
  • 测试单元中的每个方法必须可以独立测试,方法间不能有任何依赖
  • 测试类一般使用Test作为类名的后缀
  • 测试方法使一般用test作为方法名的前缀

测试失败说明:

  • Failure:一般是由于测试结果和预期结果不一致引发的,表示测试的这个点发现了问题
  • error:是由代码异常引起的,它可以产生于测试代码本身的错误,也可以是被测试代码中隐藏的bug

一些常用注解:

  • @Test:将一个普通方法修饰成一个测试方法
    • @Test(excepted=xx.class): xx.class表示异常类,表示测试的方法抛出此异常时,认为是正常的测试通过的
    • @Test(timeout=毫秒数) :测试方法执行时间是否符合预期
  • @BeforeClass: 会在所有的方法执行前被执行,static方法 (全局只会执行一次,而且是第一个运行)
  • @AfterClass:会在所有的方法执行之后进行执行,static方法 (全局只会执行一次,而且是最后一个运行)
  • @Before:会在每一个测试方法被运行前执行一次
  • @After:会在每一个测试方法运行后被执行一次
  • @Ignore:所修饰的测试方法会被测试运行器忽略
  • @RunWith:可以更改测试运行器org.junit.runner.Runner
  • Parameters:参数化注解

参数化测试:

对于一个方法需要进行多种场景进行测试时,可以通过参数化测试减少测试的工作量。用法如下:

复制代码
 1 package junit.util;
 2 
 3 import static org.junit.Assert.assertEquals;
 4 
 5 import java.util.Arrays;
 6 import java.util.Collection;
 7 
 8 import org.junit.Test;
 9 import org.junit.runner.RunWith;
10 import org.junit.runners.Parameterized;
11 import org.junit.runners.Parameterized.Parameters;
12 
13 @RunWith(Parameterized.class)
14 public class ParameterTest {
15 
16     /**
17      * 1、更改测试运行器为RunWith(Parameterized.class)
18      * 2、声明变量用来存放预期值与结果值
19      * 3、声明一个返回值为Collection的公共静态方法,并使用@Parameters进行修饰
20      * 4、位测试类声明一个带有参数的公共构造方法,并在其中为声明变量赋值
21      */
22     
23     int except;  //用来存储预期结果
24     int input1;  //用来存储第一个输入参数
25     int input2;  //用来存储第二个输入参数
26     
27     @Parameters
28     public static Collection<Object[]> initTestData(){
29     return Arrays.asList(
30         new Object[][]{
31         {3,1,2},
32         {10,5,5},
33         {6,4,2},
34         {7,3,4}}
35         );
36     }
37     
38     public ParameterTest(int except,int input1,int input2){
39     this.except = except;
40     this.input1 = input1;
41     this.input2 = input2;
42     }
43     
44     
45     
46     
47     
48     @Test
49     public void testAdd() {
50     assertEquals(except, new Claculate().add(input1, input2));
51     }
52 
53 }
原文地址:https://www.cnblogs.com/suger43894/p/10944246.html