需要注意的是: **junit的@Test注解来自org.junit,而springboottest的@Test注解来自org.junit.jupiter.api,**这种区别主要在spring boot 2.2前后,我用的是2.3.3.RELEASE
1、junit maven配置
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
junit测试类
package com.esoon.ele.web.controller.test;/**
* Created by burns.
*
* @author <a href="http://www.esoon-soft.com/">burns</a>
* @date 2021/06/24 11:21
*/
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* TODO 使用junit测试
*
* @ClassName HelloWorldControllerTest
* @Author Burns
* @DAte 2021/6/24 11:21
*/
public class HelloWorldControllerTest {
@Test
public void testSayHello(){
assertEquals("hello,world!",new HelloWorldController().syaHello());
}
}
2、spring boot test配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
从配置文件获取的配置原型类
package com.esoon.ele.web.config;/**
* Created by burns.
*
* @author <a href="http://www.esoon-soft.com/">burns</a>
* @date 2021/06/24 11:32
*/
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* TODO
*
* @ClassName appModel
* @Author Burns
* @DAte 2021/6/24 11:32
*/
@Component
@Data
public class AppModel {
@Value("${app.name}")
private String appName;
@Value("${app.version}")
private String appVersion;
}
spring boot test测试类
package com.esoon.ele.web.config;/**
* Created by burns.
*
* @author <a href="http://www.esoon-soft.com/">burns</a>
* @date 2021/06/24 11:38
*/
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
* @DAte 2021/6/24 11:38
*/
@SpringBootTest(classes = EleautoWebApplication.class)
public class AppModelTest {
@Autowired
private AppModel appModel;
@Test
public void getAppInfo(){
Assert.assertEquals(appModel.getAppName(),"eleauto");
Assert.assertEquals(appModel.getAppVersion(),"V1.0");
}
}