问题导入
回忆一下Spring整合JUnit的步骤?
1.1 Spring整合JUnit(复习)
1.2 SpringBoot整合JUnit
【第一步】添加整合junit起步依赖(可以直接勾选)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
【第二步】编写测试类,默认自动生成了一个
package org.example;
import org.example.service.BookService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest()
public class SpringbootProfileApplicationTests {
@Autowired
private BookService bookService;
@Test
public void testSave() {
bookService.save();
}
}
启动类代替了@ContextConfiguration(classes = SpringConfig.class)中SpringConfig.class类的作用
测试文件要和启动类在同一个包下,否则运行会报错
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
如果测试类和启动类不在同一个目录下,还想正常运行,可以在测试类上指定启动类
@SpringBootTest(classes = App.class)
启动运行正常