Spring integrates Junit framework

Foreword

In the previous article, I introduced to implement IOC and dependency injection in the form of annotations and XML respectively. And we have defined a test class, through which the Bean in the container is obtained. The specific test class is defined as follows:

@Test
public void test01(){<!-- -->
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    //Get Bean
    Object o = context. getBean(String id);
}

Think about it, is there any problem in defining this kind of test code?

In fact, the problem is obvious, that is, every time we define a test class, we need to write such repetitive code. Can we define a standard test template class, which can be used by both developers and testers, and this test template has a Spring environment.

In fact, Spring has provided us with a corresponding solution, that is, Spring integrates the Junit unit testing framework. Spring provides an integrated Junit4 framework and a Junit5 test framework.

Not much nonsense, let me introduce Spring to integrate the Junit framework.

Spring integrates Junit4 framework

1. What is the Junit framework

Junit is a unit testing framework written in Java language, a testing framework written by Erich Gamma and Kent Beck. Among them, Junit4 has greatly improved the entire Junit framework, and its purpose is to simplify the writing of test cases based on java annotation.

This article will not explain the use of Junit alone. We will mainly explain how to use Junit in the Spring environment. If you want to have a more comprehensive understanding of how to use Junit, you can refer to the official website of Junit: https://junit.org/junit4/

2. Using Junit4 in Spring

2.1 Introduce related dependencies

Because the Spring framework has integrated the Junit4 framework, we need to import the dependencies related to Junit4.

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.1.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.2.1.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
        <scope>test</scope>
    </dependency>
</dependencies>

You will find that in addition to referencing the dependencies of the Junit unit testing framework itself, we also introduced the dependency of spring-test.

What is this dependency? This is the dependency provided to us by Spring after integrating the Junit framework. It should be noted that the version number of this dependency is consistent with Spring’s core dependency, that is, the version number of spring-context.

2.2 Writing test cases

As before, we write a test class, but this test class is no longer the same as before. How to write it? It is the following test template class.

@RunWith(SpringJUnit4ClassRunner. class)
@ContextConfiguration(locations = {<!-- -->"classpath:applicationContext.xml"})
public class TestAccount {<!-- -->

    @Test
    public void test01(){<!-- -->
       
    }
}

Friends will find that on this test class, I added a few new annotations. The test class modified by these annotations is a standard unit test template class. So, what exactly do the two annotations that modify this class mean? Let me explain to you:

  • @RunWith
    Specifies which test engine the unit test class runs on. The following SpringJUnit4ClassRunner.class is a fixed way of writing, which means that the current Junit unit test class runs on the SpringJUnit4ClassRunner test engine.

    @ContextConfiguration
    Load Spring’s core configuration file to ensure that the current unit test template class also has a Spring environment. In this configuration class, pass locations =
    {“classpath:applicationContext.xml”}, we specify the classpath of Spring’s core configuration file. By loading the Spring core configuration file with the specified path, our unit test class also has a Spring environment.

2.3 Using the Junit unit testing framework in Spring

In the last article, we built a case of implementing ioc based on annotations. Do you still remember how our test class was written? Our previous unit test class was written as follows:

public class TestAccount {<!-- -->
    @Test
    public void test(){<!-- -->
        //1. Get the container
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //2. Get the business layer object
        AccountService accountService = ac. getBean("accountService", AccountService. class);
        //3. Execution method
        Account account = accountService. findAccountById(1);
        System.out.println(account);
    }
}

This kind of test code writing is very “cumbersome”. If we want to define multiple test methods, we need to repeatedly define the code to load the Spring configuration file, as shown below:

@Test
public void test(){<!-- -->
    //1. Get the container
    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    //The following code is omitted
}

This way of writing test code is very “cumbersome”. If we want to define multiple test methods, we need to repeatedly define loading

Because if we want to obtain beans in the Spring environment, we must define the code to load the Spring core configuration file, otherwise we cannot obtain the beans in the Spring core container. Now that we have defined this standard unit test template class, since this test class comes with the Spring environment, if we want to obtain the Bean in the container, we only need to perform dependency injection. We still combine the case in the previous article, our test case can be written in the following format:

Have you noticed that through this way of writing, our test code becomes very concise and lightweight! In fact, there are more usages of Junit integrating Spring. Here, I will introduce other usages after Spring integrates Junit4. In view of the limited space and more usages, friends can refer to the official website to learn.

2.4 Other usages of Spring integrating Junit4

(1) @Before, @After annotations

Here are two new annotations for you, one is the @Before annotation and the other is the @After annotation.

What do these two annotations mean? We can guess the general meaning by seeing the names and knowing the meaning. The @Before annotation modifies a method, which means that the currently modified method is executed before the method modified by the @Test annotation. The @After annotation also modifies a method, and the method modified by this annotation is executed after the method modified by the @Test annotation.

Now write a test case for everyone, let’s feel it:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {<!-- -->"classpath:applicationContext.xml"})
public class TestAccount {<!-- -->

    @Autowired
    AccountService accountService;

    @Before
    public void before(){<!-- -->
        System.out.println("Execute before test method...");
    }

    @After
    public void after(){<!-- -->
        System.out.println("Execute after test method...");
    }

    @Test
    public void test01(){<!-- -->
        Account account = accountService.findById(2);
        System.out.println(account);
    }
}

The specific writing method is shown in the red box in the following figure:

We run the current test case, check the console, and observe the output effect: we find that the @Before annotation modification method and the @After annotation modification method are executed before and after the @Test annotation modification method, respectively.

(2) @Ignore annotation

The @Ignore annotation modifies the corresponding test method, indicating that the current test method will not be tested and run by the Junit unit test engine, but will be ignored. We now write a test method, decorated with @Ignore annotation:
Now our test runs the entire unit test class:

Check the console: We found that the test02 method did not run, because it was modified by the @Ignore annotation, and was ignored by the unit test engine during execution.

Junit4 also provides more annotations for us to use. Here I am just throwing bricks to attract jade. If you want to use Junit4 to explain more ways to use it, please refer to the official website to learn.

Spring integrates Junit5 framework

Now let me introduce the Junit5 unit testing framework. Junit5 has derived some new features on the basis of Junit4. Let me introduce the specific features and details of Junit5:

1. Basic overview of Junit5

The Junit5 framework adopts some new styles on the basis of Junit4. It adopts the Java8 programming style, which is more flexible and robust than the Junit4 framework. Let’s take a look at the differences between it and Junit4

(1) System differences

The framework of Junit5 mainly consists of three parts: Junit Platform + Junit Jupiter + Junit Vintage3.

  • Junit Platform : Its main role is to start the test framework on the JVM. It defines an abstract TestEngine API to define the test framework running on the platform; that is to say, other automated test engines or developers? Customized engines can access Junit
    Achieve docking and execution. At the same time, it also supports running the platform through the command line, Gradle and Maven (this is very important for us to do automated testing)

    Junit Jupiter: This is the core of Junit5, which can be regarded as the evolution of the original functions of Junit4, including the latest programming model and extension mechanism of JUnit 5; many rich new features make JUnit
    ?Automated testing is more convenient, with richer and more powerful functions. It is also the place where the test needs to focus on learning; Jupiter itself? A Junit Platform-based
    engine implementation of JUnit 5, the JUnit Jupiter API is just another API

    Junit Vintage3Junit After more than 10 years of development, both Junit 3 and Junit 4 have accumulated a large number of users. As a new generation framework, this module is a test engine compatible with JUnit3 and JUnit4 versions, making the old version of junit The automated test scripts can also run smoothly in Junit5
    Next, it can also be regarded as an engine paradigm implemented based on Junit Platform.

(2) Differences in use

Most of the annotations are the same in JUnit4 and JUnit5, but some are different. Here is a table to list them for you:

After figuring out the difference between the Junit5 and Junit4 unit testing frameworks, let’s take a look at the specific use of the Junit5 unit testing framework.

2. Using Junit5 in Spring

2.1 Introduce related dependencies

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.9.RELEASE</version>
</dependency>


<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.6.2</version>
</dependency>

<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-runner</artifactId>
    <version>1.6.2</version>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>RELEASE</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-launcher</artifactId>
    <version>1.6.2</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.6.2</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    <version>5.6.2</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-params</artifactId>
    <version>5.6.2</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.0.9.RELEASE</version>
    <scope>provided</scope>
</dependency>

2.2 Writing test cases

Now we write a standard test case. Note that the annotations used by this test case are different from those used by the Junit4 unit test framework.

package com.qf;

import com.qf.service.AccountService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension. class)
@ContextConfiguration("classpath:applicationContext.xml")
//@SpringJUnitConfig(locations = "applicationContext.xml")// Combined annotations @ExtendWith + @ContextConfiguration
public class MyTest2 {<!-- -->
    
    @Autowired
    AccountService accountService;

    @Test //Note that this annotation is no longer under the org.junit package, but org.junit.jupiter.api.Test;
    public void Tg() {<!-- -->
        accountService. transfer("eric", "james", 500.0);
    }
}

After testing, we found no problem. Next, let’s learn other usages after Spring integrates Junit5.

2.3 Other usages of Spring integrating Junit5

(1) Common annotations of Junit5

@DisplayName : Decorate the test class or test method, and set the display name for the test class or test method. Now write a test case for everyone:

@BeforeEach : Indicates that it is executed before each unit test. We will show you how to use this annotation:

@BeforeEach
public void beforeEach(){<!-- -->
    System.out.println("This is the beforeEach method");
}


We run the test01 method and find that the output of the console result is as follows:

@AfterEach: means to execute after each unit test, we continue to demonstrate the use of this annotation:

@AfterEach
public void afterEach(){<!-- -->
    System.out.println("This is the afterEach method");
}


We run the test01 method and find that the console output is as follows:

Summary

Through this article, I will give you a detailed introduction to how Spring integrates the Junit framework. And demonstrate the specific usage of Spring’s integration of Junit4 and Junit5 unit test framework

These two methods will be used in future study and work, so you must master and learn to use them