[Java] Junit test class

Test Category

  1. Black box testing: no need to write code to the input value to see if the program can output a desired value.
  2. White-box testing: the need to write code. Specific attention program execution flow. Junit for white-box testing

Junit use the steps

  1. Define a class test (test)
* 测试类名:被测试的类名Test     CalculatorTest
* 包名:xxx.xxx.xx.test      cn.itcast.test
  1. Define the test: You can run independently
* 方法名:test测试的方法名      testAdd()
* 返回值:void
* 参数列表:空参
  1. Method to add @Test

  2. Import junit depend on the environment

* 判定结果:
* 红色:失败
* 绿色:成功
* 一般我们会使用断言操作来处理结果
* Assert.assertEquals(期望的结果,运算的结果);
  1. supplement:
* @Before:
* 修饰的方法会在测试方法之前被自动执行
* @After:
* 修饰的方法会在测试方法执行之后自动被执行

Sample Code

Custom class code

/**
 * 计算器类
 */
public class Calculator {


    /**
     * 加法
     * @param a
     * @param b
     * @return
     */
    public int add (int a , int b){
        //int i = 3/0;

        return a - b;
    }

    /**
     * 减法
     * @param a
     * @param b
     * @return
     */
    public int sub (int a , int b){
        return a - b;
    }

}

Do not use the test class, test, need to constantly comment inconvenient

public class CalculatorTest {

    public static void main(String[] args) {

        //创建对象
        Calculator c = new Calculator();
        //调用
       /* int result = c.add(1, 2);
        System.out.println(result);*/

        int result = c.sub(1, 1);
        System.out.println(result);

        String str = "abc";
    }
}

Test class code, add comments @test, this part of the code can be run independently, no longer in the running for the main method

import cn.itcast.junit.Calculator;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class CalculatorTest {
    /**
     * 初始化方法:
     *  用于资源申请,所有测试方法在执行之前都会先执行该方法
     */
    @Before
    public void init(){
        System.out.println("init...");
    }

    /**
     * 释放资源方法:
     *  在所有测试方法执行完后,都会自动执行该方法
     */
    @After
    public void close(){
        System.out.println("close...");
    }


    /**
     * 测试add方法
     */
    @Test
    public void testAdd(){
       // System.out.println("我被执行了");
        //1.创建计算器对象
        System.out.println("testAdd...");
        Calculator c  = new Calculator();
        //2.调用add方法
        int result = c.add(1, 2);
        //System.out.println(result);

        //3.断言  我断言这个结果是3
        Assert.assertEquals(3,result);

    }

    @Test
    public void testSub(){
        //1.创建计算器对象
        Calculator c  = new Calculator();
        int result = c.sub(1, 2);
        System.out.println("testSub....");
        Assert.assertEquals(-1,result);
    }
}
Published 238 original articles · won praise 6 · views 20000 +

Guess you like

Origin blog.csdn.net/u011035397/article/details/105184614