A simple summary and code samples of easy-to-understand java Junit unit tests

Insert picture description here
Insert picture description here
Code sample:
2 classes
Insert picture description here

public class calculator {
    
    
    int add(int x,int y){
    
    
        return  x+y;
    }
    int subtract(int x,int y){
    
    
        return x-y;
    }
    int multiply(int x,int y){
    
    
        return x*y;
    }
    int division(int x,int y){
    
    
        return x/y;
    }

}

Insert picture description here

import org.junit.Assert;
import org.junit.Test;
public class test {
    
    
    @Test
    public void testadd(){
    
    
        calculator yf=new calculator();
        int result =yf.add(1,2);
        Assert.assertEquals(3,result);
        System.out.println("...........................");

    }


}

Because it is indeed equal to 3, the code is output normally, as follows.

If it is not equal to

import org.junit.Assert;
import org.junit.Test;
public class test {
    
    
    @Test
    public void testadd(){
    
    
        calculator yf=new calculator();
        int result =yf.add(1,2);
        Assert.assertEquals(2,result);//修改在这
        System.out.println("...........................");

    }


}

The result is as follows, the
Insert picture description here
compiler will automatically report an error

Insert picture description here
Code sample
only make changes to test


import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class test {
    
    
    @Before
    public void before(){
    
    
        System.out.println("这里是before");
    }
     @After
     public void after(){
    
    
        System.out.println("after");
    }


    @Test
    public void testadd(){
    
    
        calculator yf=new calculator();
        int result =yf.add(1,2);
        Assert.assertEquals(2,result);
        System.out.println("...........................");

    }


}

Insert picture description here
We don’t see the execution order of after here.
Let’s change the code to

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class test {
    
    
    @Before
    public void before(){
    
    
        System.out.println("这里是before");
    }
     @After
     public void after(){
    
    
        System.out.println("after");
    }


    @Test
    public void testadd(){
    
    
        calculator yf=new calculator();
        int result =yf.add(1,2);
        Assert.assertEquals(3,result);
        System.out.println("...........................");

    }


}

Insert picture description here
This is obvious

Guess you like

Origin blog.csdn.net/jahup/article/details/106035725