一、junit官网

junit4:http://junit.org/junit4/

junit5:http://junit.org/junit5/

二、github

junit4: https://github.com/junit-team/junit4

junit5: https://github.com/junit-team/junit5

三、下载和安装

https://github.com/junit-team/junit4/wiki/Download-and-Install

三、junit4运行流程

@Test

讲一个普通的方法修饰成测试方法

@BeforeClass

修饰的方法会在所有的方法调用前被调用,

而且该方法是静态的,所以当测试类被加载后就会运行他,

而且在内存中他只会存在一份实例,比较适合加载配置文件

@AfterClass 修饰的方式通常用来对资源的清理,如关闭数据库的连接
@Before 会在每个@Test修饰的方法的前各执行一次
@After 会在每个@Test修饰的方法的后各执行一次

三、junit4常用注解

1.@Test

1)@Test的两个属性

属性名 作用 实例
expected 声明了该测试方法应该抛出一个异常,如果抛出了说明测试成功 @Test{expected=XX.class}
timeout

设置测试方法的超时时间,超过时间测试方法就会停止

适用场景举例:比如有一个循环代码,循环控制条件不太好控制,这里

使用timeout就避免了一直等待

@Test{timeout=毫秒}

2.@Ignore

代表所修饰的测试方法会被测试运行器所忽略

3.@RunWith

可以更改测试运行器,自定义自己的运行器(必须继承org.junit.runner.Runner)

四、断言的使用

具体使用方法可参考官方文档:https://github.com/junit-team/junit4/wiki/Assertions

五、测试套件的使用

当有多个测试类,一个一个测试太麻烦了,可以使用如下测试套件

package com.dechy.test;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({TaskTest1.class,TaskTest2.class,TaskTest3.class})
public class SuiteTest {
/**
* 1.测试套件就是组织测试类一起运行
*
* 写一个作为测试套件的入口类,这个类中不包含其他方法
* 更改测试运行器Suite.class
* 将要测试的类作为数组传到Suite.SuiteClasses({})
*/

}

 六、junit的参数化设置

package com.dechy.util;

import static org.junit.Assert.*;

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

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class ParameterTest {
    /*
     * 1.更改默认的测试运行器为RunWith(Parameterized.class)
     * 2.声明变量来存放预期值 和结果值
     * 3.声明一个返回值 为Collection的公共静态方法,并使用@Parameters进行修饰
     * 4.为测试类声明一个带有参数的公共构造函数,并在其中为之声明变量赋值
     */
    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 ParameterTest(int expected,int input1,int input2) {
        this.expected = expected;
        this.input1 = input1;
        this.input2 = input2;
    }
    
    @Test
    public void testAdd() {
        assertEquals(expected, new Calculate().add(input1, input2));
    }

}

 

posted on 2017-11-08 16:57  knyel  阅读(328)  评论(0编辑  收藏  举报