在 Spring boot 测试中为组件扫描配置基础包 [英] Configuring base package for component scan in Spring boot test

查看:20
本文介绍了在 Spring boot 测试中为组件扫描配置基础包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用以下注释启动我的测试时:

When I launch my test with the following annotations:

package com.hello.package.p1;

@RunWith(SpringRunner.class)
@DataMongoTest
@SpringBootTest
public class ClassATest {

@Autowired
Service1 serivce1; //fqn = com.hello.package.p1.Service1 

@Autowired
Service2 serivce2; //fqn = com.hello.package.p2.Service2 

...}

package com.hello.package.p1;

@ActiveProfiles("test")
@SpringBootConfiguration
public class MongoTestConfig {
...
}

service1 将被注入.但是 service2 不会,因为它与测试类不在同一个包中.我收到一个错误:

service1 will be injected. But service2 will not, since it is not in the same package as the test class. I get an error:

通过字段'service2'表达的不满意的依赖;嵌套例外是org.springframework.beans.factory.NoSuchBeanDefinitionException

Unsatisfied dependency expressed through field 'service2'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException

如何告诉我的测试上下文我想加载/扫描某个包,例如 com.hello?

How can I tell my testing context that I want to load/scan a certain package, for example com.hello?

推荐答案

您可以在测试包中添加一个 TestConfig 类:

You can add a TestConfig class in your test package:

@Configuration
@ComponentScan({ "com.hello.package.p1", "com.hello.package.p2" })
public class TestConfig {
}

这篇关于在 Spring boot 测试中为组件扫描配置基础包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆