1. What is Junit4

Junit 4 is an easy to learn and easy to use Java unit testing framework, generally we write a piece of code or a party, all want to test this code and the logic of this method is correct, the input data, the data returned is the results we want, that we are writing a single business code for testing on the results. This is where Junit comes in handy.

2. Why Junit4

Maybe some beginners will say, can’t you test after the project is finished? If that’s what you want to think about it, because the more you code, the more you get involved in modules and the more logic in your project, which makes testing very cumbersome and error-prone. Junit may seem to increase the amount of code, but it can greatly reduce late testing time, improve the quality of the code, and make the code easier to maintain.

3. Quick start with Junit4

Download and import the Junitjar package:

First, you need to download a Junit4 JAR package from the Internet, save it to your local computer, open myEclipse and create a new Java project. Right-click the project >Build Path >Configure Build Path >Add External JARs > find the jar Path you saved and click OK

Create test directory:

The next step is to create a special path for our tests. What makes this special is that our test code should be kept separately and not confused with the source code. It can be deleted at the end of the project without affecting the project. To create one, right click on the project name –>new—-> Suorce Folder –> Enter the test file name you want and click OK.

Next we need to create a package in the SRC directory of the project, and make sure that the package name is the same as the package name in the test directory. In our SRC package, we write our logical method, and in the test package, we write our test method.





image.png

Let’s write a simple logical code to test the drill

package com.junit;

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

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

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

    public int division(int a, int b) {
        returna / b; }}Copy the code

Create a new test class junit_test in our test directory and define the test method. The code is as follows:

package com.junit;
import static org.junit.Assert.*;
import org.junit.Test;
public class junit_test {

    
    // The test method must have @test;
    // The test method must be public void and return no value;
    // This method takes no parameters;
    // Create a test file to store the test code separately;
    // The package of the tested class is the same as the package of the tested class;
    // Test methods are independent of each other without any dependencies;
    @Test
    public void testAdd(a){
        
        assertEquals(4.new method_junti().add(3.0));
    }
    
    @Test
    public void testSubtract(a){
        assertEquals(3.new method_junti().subtract(6.3));
    }
    
    @Test
    public void testMultiply(a){
        assertEquals(6.new method_junti().multiply(6.1));
    }
    
    @Test
    public void testDivision(a){
        assertEquals(6.new method_junti().division(6.1)); }}Copy the code

AssertEquals () is a function whose first argument is the result you expect, and the second argument is the function we want to test. This function is called by first new out of the class of the function and then by calling the method from the class. The arguments in the method are the arguments that you passed in when you wrote the method. It is best to add test to the method you need to test, so that it is more formal

When you’re done, you can click on the test class, then click On Run as, then click Junit Test, and you’ll see your test results in a pop-up window that will show you the number of failures and the number of errors. If you only want to test one method, there is a directory under the test class you created that lists all your test methods. You can right-click the method you want to test and then run as –> junit Test. When the test succeeds, you will see a green bar.





image.png

Here if we have to manually every method on its test methods, here we just simple test methods, in the project need to test if we have a lot of methods, one by one to knock it will waste some time, here to introduce a fast generating test method is a method: SRC: method_junit. Java — right click new– > see if Junit test case is in the prompt box. If not, click Other. In the dialog box that pops up, go to the Source Folder and click Browse to change it to the directory that contains Test. Some of these directories may have duplicate names. Just change the Name below -> next- > you’ll see all the methods in method_junit, so you can select them and create the following test method:

package com.junit;
import static org.junit.Assert.*;
import org.junit.Test;
public class method_juntiTest2 {

    @Test
    public void testAdd(a) {
        fail("Not yet implemented");
    }

    @Test
    public void testSubtract(a) {
        fail("Not yet implemented");
    }

    @Test
    public void testMultiply(a) {
        fail("Not yet implemented");
    }

    @Test
    public void testDivision(a) {
        fail("Not yet implemented"); }}Copy the code

Delete the statement after fail and write what you want to test.

4. Two cases of junit test failure:

In front of the case we are testing are examples of success, but the role of Junit only in the test method of data returned is correct, but the data we may not return the correct situation is right, for example if you are asking for is the area of the rectangle, but you are using the perimeter formula, when you are in the test he will also give you test success, Get the expected result, which means our test case is powerless against logic errors

A test failure occurs when the expected value is not the same as the result of the program’s execution: for example, we tested the addition function above:

@Test
public void testAdd(a){
      assertEquals(3.new method_junti().add(3.0));
}
Copy the code

If you change the expected result from 3 to 4, the test fails. Failure is followed by a 1 indicating a test failure, which is visible at run time. If you look closely, there are hints below, as shown in the picture:





image.png

Test failure 2: Let’s test division:

@Test
public void testDivision(a){
    assertEquals(6.new method_junti().division(6.1));
}
Copy the code

Here’s what happens if you change the divisor to 0: The error number in the following prompt box changes to 1; There is an error. So we get the following two situations:

1, the general method used by a unit test the assertion failure judgment caused by the failure, which means that the test points found the problem, that is the result of the program output and the expected is not the same as 2, the error is caused by abnormal code, he may be due to the test error of the code itself, also may be hiding a bug in the test code

5. Junit’s running process:

Create a new junit case in com.junit under test and name it junit_case. Select setUpBeforeClass(), tearDownAfterClass(), setUp(), tearDown() at creation time to get the following code:

package com.junit;

import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;


public class Junit_case {
    @BeforeClass
    public static void setUpBeforeClass(a) throws Exception {}@AfterClass
    public static void tearDownAfterClass(a) throws Exception {}@Before
    public void setUp(a) throws Exception {}@After
    public void tearDown(a) throws Exception {}@Test
    public void test(a) {
        fail("Not yet implemented"); }}Copy the code

Let’s enter a simple output statement for each method to see how it works, as follows:

package com.junit;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class Junit_test1 {

    
    /* 1, BeforeClass methods are executed before all methods are called * and the method is static, so it is executed after the test class is loaded * there is only one copy of it in memory, suitable for loading configuration files * 2, AfterClass methods are used to clean up resources. If there are two * test files, before and after are executed twice each; if there are two * test files, before and after are executed twice each. * * /
    @BeforeClass
    public static void setUpBeforeClass(a) throws Exception {
        System.out.println("this is beforeclass");
    }

    @AfterClass
    public static void tearDownAfterClass(a) throws Exception {
        System.out.println("this is afterclass");
    }

    @Before
    public void setUp(a) throws Exception {
        System.out.println("this is before");
    }

    @After
    public void tearDown(a) throws Exception {
        System.out.println("this is after");
    }

    @Test
    public void test1(a) {
        System.out.println("this is test1"); }}Copy the code

If you run the code above, you get the following result

6. Junit

I have already explained above @ test, @ BeforeClass, @ AfterClass, @ Before, @ After these annotations, a visible on this guy’s blog, provide address below: blog.csdn.net/zixiao217/a… For @test, in addition to decorating a normal method as a test method, it can handle exceptions and set timeouts. The expected and timeout parameters for test are expected and timeout. The expected and timeout parameters for test are expected and timeout. The expected and timeout parameters for test are expected and timeout.

@Test(expected=ArithmeticException.class)
public void testDivision(a){
     assertEquals(6.new method_junti().division(6.0));
}
Copy the code

It is necessary to set a timeout when testing some performance-critical methods. It can be used to check whether your code will run within this period of time, as follows:

@Test(timeout=2000)// Milliseconds
 public void testWhile(a){
    while(true){
        System.out.println("run forever"); }}Copy the code

@ignore: If you add this modifier to the test method, the test method will not be executed. @runwith can change the test runner; In addition to using the test runners provided by junit, we can also customize our runners by inheriting org.junit.runner.Runner code as follows:

import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@Suite.SuiteClasses({TaskTest1.class,TaskTest2.class,TaskTest3.class})
public class SuitTest {
    
    public void test(a){
        /* * Write a test suite that combines all the classes that need to be tested. * 1. Write a test entry class that contains no other methods. @runwith (Suite. Class) @suiteclasses ({}); * /}}Copy the code

7. Junit parameter Settings

In the above tests, we only tested one set of data for each method, but in real projects, one set of data is often not enough. We need many sets of data, and it would be exhausting to write a test method for each array. We can use parameter Settings to solve this problem. The code is as follows:

package com.junit;
import static org.junit.Assert.*;

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

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class ParameterTest {
    // Declare variables to store expected values and test data;
    int expected=0;
    int input1=0;
    int input2=0;
    
    @Parameters
    public static Collection<Object[]> test(){
    
        return Arrays.asList(new Object[][]{
                {3.1.2},
                {4.2.2}}); }public ParameterTest(int expected,int input1,int input2){
        this.expected=expected;
        this.input1=input1;
        this.input2=input2;
    }
    @Test
    public void testAdd(a){
        assertEquals(expected, newmethod_junti().add(input1, input2)); }}Copy the code

We need to test multiple sets of data, so we need Arrays to hold multiple sets of data, which is received using arrays.aslist.