junit unit testing

Use of junit: white box testing

Steps:

1. Define a test class (test case)

* Test Class Name: The Class Name under Test, e.g.Calculator

* Package name: xxx.xxx.xx.test

2. Define test methods: they can run independently

* Method Name: Method Name of test Test test, e.g. testAdd()

* Return value: void

* Parameter list: empty parameter

3. Add @Test to the method

4. Importing junit dependency environment

Decision result

Red: Failure

Green: Success

Generally, assertion operations are used to process results

* Assert. assertEquals (expected results, operation results);

 

Calculator.java

package cn.zh.junit;

/**
 * Calculator class
 */
public class Calculator {


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

        return a - b;
    }

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

}

 CalculatorTest.java

package cn.zh.test;

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

public class CalculatorTest {
    /**
     * Initialization method:
     *  For resource applications, all test methods execute this method before execution
     */
    @Before
    public void init(){
        System.out.println("init...");
    }

    /**
     * Method of releasing resources:
     *  After all test methods are executed, the method is automatically executed
     */
    @After
    public void close(){
        System.out.println("close...");
    }


    /**
     * Test add method
     */
    @Test
    public void testAdd(){
       // System.out.println("I'm executed");
        //1. Create calculator objects
        System.out.println("testAdd...");
        Calculator c  = new Calculator();
        //2. Call the add method
        int result = c.add(1, 2);
        //System.out.println(result);

        //3. To assert that I assert that the result is 3
        Assert.assertEquals(3,result);

    }

    @Test
    public void testSub(){
        //1. Create calculator objects
        Calculator c  = new Calculator();
        int result = c.sub(1, 2);
        System.out.println("testSub....");
        Assert.assertEquals(-1,result);
    }
}

 

Tags: calculator Junit Java

Posted on Sun, 06 Oct 2019 12:53:00 -0700 by Bluelove