In junit unit tests, there is a Test annotation. The method under the Test annotation can be run directly, just like the main method, and multiple Test annotations can be written in a class, which is convenient for testing code. For the Test method, if the execution is successful, there will be a green check box, otherwise there will be a Red Cross

Two other common comments under junit are the Before annotation, where the method is executed at the beginning of the program execution, equivalent to initialization, and the After annotation, which is executed at the end of the program execution, equivalent to freeing resources

Here I use a calculator example to demonstrate, first write a Cal calculator class, there are two methods, respectively addition and subtraction

public class Cal {
    public int add(int a,int b) {
        return a + b;
    }

    public int sub(int a,int b){
        returna - b; }}Copy the code

When we want to test the above method we can create a new class

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class CalTest {
    @Before
    public void init(a){
        System.out.println("init...");
    }

    @After
    public void close(a){
        System.out.println("close...");
    }

    @Test
    public void testAdd(a){
        Cal c = new Cal();
        int result = c.add(1.2);
        The predicate operation processes the result, where the first argument is our expected argument and the second is the run result
        Assert.assertEquals(3,result);
        System.out.println("testAdd...");
    }

    @Test
    public void testSub(a){
        Cal c = new Cal();
        int result = c.sub(1.2);
        // Test with an error result here, and see what the result is
        Assert.assertEquals(2,result);
        System.out.println("testSub..."); }}Copy the code

By testing under the Test annotation method of this class, we Test a true example and a false example

The first addition is correct and the result is as follows

The second subtraction operation results in an error, as follows

Of course, you can see from the above that the Before and After annotations are executed regardless of the result of the run, right