Note that: ** Junit’s @test annotation comes from org.junit and Springboottest’s @test annotation comes from org.junit.jupiter. API. ** This difference is mainly around Spring Boot 2.2, I use 2.3.3.RELEASE
1. Junit Maven configuration
<dependency> <groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency>Copy the code
Junit test class
package com.esoon.ele.web.controller.test;/**
* Created by burns.
*
* @author <a href="http://www.esoon-soft.com/">burns</a>
* @date2021/06/24 * / calling
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/** * TODO uses junit test **@ClassName HelloWorldControllerTest
* @Author Burns
* @DAte2021/6/24 * / calling
public class HelloWorldControllerTest {
@Test
public void testSayHello(a){
assertEquals("hello,world!".newHelloWorldController().syaHello()); }}Copy the code
2. Configure spring Boot Test
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
Copy the code
The configuration stereotype class obtained from the configuration file
package com.esoon.ele.web.config;/**
* Created by burns.
*
* @author <a href="http://www.esoon-soft.com/">burns</a>
* @date2021/06/24 11:32 * /
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* TODO
*
* @ClassName appModel
* @Author Burns
* @DAte2021/6/24 11:32 * /
@Component
@Data
public class AppModel {
@Value("${app.name}")
private String appName;
@Value("${app.version}")
private String appVersion;
}
Copy the code
Spring Boot Test Tests a class
package com.esoon.ele.web.config;/**
* Created by burns.
*
* @author <a href="http://www.esoon-soft.com/">burns</a>
* @date2021/06/24 though * /
import com.esoon.ele.web.EleautoWebApplication;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* TODO
*
* @ClassName AppModelTest
* @Author Burns
* @DAte2021/6/24 though * /
@SpringBootTest(classes = EleautoWebApplication.class)
public class AppModelTest {
@Autowired
private AppModel appModel;
@Test
public void getAppInfo(a){
Assert.assertEquals(appModel.getAppName(),"eleauto");
Assert.assertEquals(appModel.getAppVersion(),"V1.0"); }}Copy the code
Reference: www.jianshu.com/p/bdd22240f… Blog.csdn.net/qq_42580533…