Java unit testing tool for software quality and testing: JUnit4 learning

preface

JUnit is a unit test framework of Java programming language, which is a simple framework for writing reusable test sets. JUnit has a very important development in test driven development. It is one of the unit testing frameworks collectively called xUnit, which originated from JUnit. XUnit is a test framework based on test driven development, including Python unit, CppUnit, JUnit, etc.
Junit test is a programmer test, that is, the so-called white box test, because the programmer knows How and What functions the tested software completes.

1, Basic usage examples

Open the class to be tested, press the shortcut key ctrl + shift + t, select Create New Test, and check the method to be tested in the lower Member of the dialog box.

Method to be tested:

public class Caculator {
    public int add(int a, int b) {
        //Deliberately set the adder to error
        return a + b -1;
    }

    public int subtract(int a, int b) {
        return a - b;
    }

    public int multiply(int a, int b) {
        return a * b;
    }

    public int divide(int a, int b) {
        return a / b;
    }
}


Write test code:

public class CaculatorTest {
    Caculator caculator = new Caculator();

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void add() {
        int result = caculator.add(2, 3);
        /*
         * @param
         * message:Error message
         * expected:Expected value
         * actual:actual value
         */
        Assert.assertEquals("something wrong with function add()", 5, result);
    }


    @Test
    public void subtract() {
        int result = caculator.subtract(3, 1);
        Assert.assertEquals("something wrong with function subtract()", 2, result);
    }

    @Test
    public void multiply() {
    }

    @Test
    public void divide() {
    }
}

Test results:

2, Detailed explanation of use

1. JUnit assertion

All Junit assertions are contained in the Assert class.
This class provides many useful assertion methods to write test cases. Only failed assertions are recorded. Some methods in the Assert class are listed as follows:

void assertEquals(boolean expected, boolean actual):Check whether two variables or equations are balanced
void assertTrue(boolean expected, boolean actual):Check condition is true
void assertFalse(boolean condition):The inspection condition is false
void assertNotNull(Object object):Check object is not empty
void assertNull(Object object):Check object is empty
void assertSame(boolean condition):assertSame() Method to check whether two related objects point to the same object
void assertNotSame(boolean condition):assertNotSame() Method to check whether two related objects do not point to the same object
void assertArrayEquals(expectedArray, resultArray):assertArrayEquals() Method to check whether two arrays are equal

2. JUnit annotation

@Test:This note indicates that attached to JUnit of public void Method can be used as a test case.
@Before:Some tests need to create several similar objects before running. stay public void Method is annotated because the method needs to test Method.
@After:If you put external resources in Before Method, then you need to release them after the test runs. stay public void Method is annotated because the method needs to test Method.
@BeforeClass:stay public void Method is annotated because it needs to be run before all methods in the class, static modification.
@AfterClass:It will enable the method to be executed after all tests are completed and can be used for cleaning activities, static modification.
@Ignore:The modified test method will be ignored by the test runner

JUnit annotation execution process

beforeClass(): Method is executed first and only once.
afterClass():Method is executed last and only once.
before():Method is executed for each test case, but before executing the test case.
after():Method is executed for each test case, but after the test case is executed.
//Execute each test case between the before() method and the after() method.

3. JUnit time test

If a Test case takes more time than the specified number of milliseconds, Junit will automatically mark it as a failure. The timeout parameter (in milliseconds) is used with the @ Test annotation.

@Test(timeout=1000)

4.JUnit test suite

Integrate the test classes to be run into our test Suite. For example, a system function corresponds to a test Suite, and a test Suite contains multiple test classes. Each time the system function is tested, just execute the test Suite once. Bundle several unit test cases and execute them together. In JUnit, @ RunWith and @ Suite annotations are used to run Suite tests.

@Runwith(Suite.class)
@Suite.SuiteClasses({
		Test1.class,
		Test2.class
})//Suite. Put the test classes of the test suite into suitecasses() in the form of an array {class1,class2,...} As a parameter
public class TestSuite{
	//...
}

3, Parametric settings

Steps:
① To perform parametric testing, you need to specify the following runner on the class:

  @RunWith (Parameterized.class)

② Then, add an @ Parameters annotation to the method providing data. This method must be static and return a Collection.
③ Assign values to each parameter in the construction method of the test class (the construction method is called by JUnit), and finally write the test class, which will run the test multiple times according to the number of groups of parameters.

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;
import java.util.Collection;

import static org.junit.Assert.assertEquals;

@RunWith(Parameterized.class)
public class GetRowTest {
    //Test function: in the four piece chess game, return the row of the chess piece after the current player confirms to place the piece in column col
    //Represents the current chessboard matrix to be tested
    @Parameterized.Parameter(0)
    public int[][] checkBoard;

    //Indicates the column to which the drop belongs
    @Parameterized.Parameter(1)
    public int colum;

    //Expected number of rows returned
    @Parameterized.Parameter(2)
    public int expected;

    //Detected object
    Board board;

    @Parameterized.Parameters(name = "{index}:getRow[{0},{1}]={2}")
    public static Collection data() {
        return Arrays.asList(new Object[][]{
        		//The first parameter is the current chessboard, and the second and third parameters are the currently selected sub column and the expected return row
        		//In column 5 (colum=4), the number of rows that should be returned is row 3 (expected=2)
                {new int[][]{{1, 2, 1, 2, 1, 2, 1},
                        {2, 1, 2, 1, 2, 1, 2},
                        {0, 0, 0, 0, 0, 0, 0},
                        {0, 0, 0, 0, 0, 0, 0},
                        {0, 0, 0, 0, 0, 0, 0},
                        {0, 0, 0, 0, 0, 0, 0}}, 4, 2},
				//In column 7 (colum=6), the number of rows that should be returned is row 1 (expected=0)
				//Try changing expected to 1 here
                {new int[][]{{1, 1, 1, 1, 0, 0, 0},
                        {2, 2, 2, 0, 0, 0, 0},
                        {0, 0, 0, 0, 0, 0, 0},
                        {0, 0, 0, 0, 0, 0, 0},
                        {0, 0, 0, 0, 0, 0, 0},
                        {0, 0, 0, 0, 0, 0, 0}}, 6, 1},

    }


    @Before
    public void setUp() throws Exception {
        board = new Board();
        System.out.println("setUp");
    }

    @After
    public void tearDown() throws Exception {
        board = null;
        System.out.println("tearDown");
    }

    @Test
    //After completing the test method, the test of multiple groups of data will be completed automatically
    public void getRow() {
        board.setBoard(checkBoard);
        assertEquals(expected, board.getRow(colum));
    }
}

Test results:


Note: in the above code, this section is equivalent to implementing the constructor of the test class.

@Parameterized.Parameter(0)
public int[][] checkBoard;
@Parameterized.Parameter(1)
public int colum;
@Parameterized.Parameter(2)
public int expected;
@Parameterized.Parameters
public static Collection data(){
	//···
}

The following code can be used instead:

public int[][] checkBoard;
public int colum;
public int expected;
public GetRowTest( int[][] checkBoard,int colum, int expected) {
        this.expected = expected;
        this.checkBoard = checkBoard;
        this.colum = colum;
        }

summary

Courseware notes


Keywords: Java Junit unit testing software testing

Added by SteveFrost on Fri, 04 Mar 2022 20:39:17 +0200