一.学习背景
在编写SpringBoot项目时,需要对Service层进行测试,这样可以减少测试成本,那如何对Service层进行测试呢?
二.步骤
引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.4.0-M4</version>
</dependency>
确保spring-boot-starter-test的版本号和spring-boot-starter-web的版本号保持一致。
三.测试
在test文件下新建包名,和main/java下的包名保持一致,比如如下这样:
启动类代码如下:
@SpringBootApplication(scanBasePackages={"com.demo"})
public class ApplicationTest{
public static void main(String[] args){
SpringApplication.run(ApplicationTest.class,args);
}
}
Test文件下的代码如下:
@RunWith(SpringRunner.class)
@SpringBootTest
public class Test {
@Resource
private UserService userService;
@org.junit.Test
public void test(){
String name=userService.getName();
System.out.println(name);
}
}
踩坑:
1.启动类飘红:直接放在了java目录下,需要放在包下(如图中的com.demo下)
2.报错如下:java.lang.IllegalStateException: Could not load TestContextBootstrapper [null]
这种问题就是前面提到的:确保spring-boot-starter-test的版本号和spring-boot-starter-web的版本号保持一致。
3.如果项目中存在多个yaml文件,可以在代码中添加@ActiveProfiles("dev")用来指定运行哪个yaml文件,如下: