Junit入门教程

做开发的时候,完成一个接口、方法、函数或者功能等,需要测试,是否有bug,有逻辑错误。这里有两种方案测试

1. 在main中写测试方法

2. 使用开源框架,这里使用的junit

main写测试方法优点:

  1.简单粗暴,基本没有学习成本

  2. 暂时没想到

main写测试方法缺点:

  1. 如果要测多个方法,代码会很乱

  2. 测试代码属于浸入式代码

使用开源框架junit:

优点:

  1. 可以针对每个方法写一个测试方法,每个测试方法可以单独执行

  2. 代码没有侵入性,不会污染原来的代码

  3. 很容易上手,学习成本基本为0

使用方法:

1. 引入junit jar包

<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

备注:Junit5已经出来了

2. 要测试的程序demo

HelloJunit.java

/**
 * Created by 58 on 2017/12/10.
 */
public class HelloJunit {
    public void hello(){
        System.out.println("Welcome to junit.");
    }
}

3. 写测试方法

TestHello.java

import org.junit.Before;
import org.junit.Test;

/**
 * Created by 58 on 2017/12/10.
 */
public class TestHello {
    private HelloJunit helloJunit = null;

    @Before
    public void init(){
        System.out.println("Do init.");
        helloJunit = new HelloJunit();
    }

    @Test
    public void testHello(){
        helloJunit.hello();
    }
}

说明,添加@Before可以在T@Test注解的方法前进行初始化操作

原文地址:https://www.cnblogs.com/luckygxf/p/8017249.html