我正在尝试使用 Controller 、服务和存储库(SPRING DATA)在 Spring Boot 中应用单元测试,但是当我尝试执行测试时,并向我显示此消息。
Field parameterRepository in ParameterService required a bean of type ParameterRepository that could not be found.
我将@repository放入我的接口(interface)存储库中,但是不起作用。
我将部分代码附加到您的帮助中。
@RunWith(SpringRunner.class)
@WebMvcTest(value = ParameterController.class, secure = false)
@ContextConfiguration(classes = {ParameterController.class, ParameterService.class, ParameterRepository.class})
public class ParameterTest {
@Autowired
private WebTestClient webClient;
@Test
public void getParamterById() {
this.webClient.get().uri("/parameters/v1").exchange().expectStatus().isOk();
}
}
public interface ParameterRepository extends MongoRepository<Parameter, ObjectId>{
Optional<Parameter> findByCode(String code);
}
有人知道如何在 Spring 中测试解决这个问题吗?
最佳答案
您的@ContextConfiguration
未指向您的@Configutation
类。您不需要将 Controller 和服务类传递给 ContextConfiguration。
@ContextConfiguration(classes = {ParameterController.class, ParameterService.class, ParameterRepository.class})
<小时/>
您可以有一个单独的类@TestConfiguration,它将默认扫描并加载当前包和子包中的所有类。
@TestConfiguration
public class MyTestConfiguration {
将此测试配置类传递给您的@ContextConfiguration
@ContextConfiguration(classes={MyTestConfiguration.class})
<小时/>
如果您的测试配置不在包层次结构的顶部
你可以像这样使用@ComponentScan
@ComponentScan({"com.my.package.first","com.my.package.second"})
关于java - 使用 Controller -> 服务 -> 存储库对 Spring Boot 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52827977/