java - Spring Boot 测试 - 没有可用的“com.example.MyService”类型的合格 bean
问题描述
stackoverflow 上有很多类似的问题,但我发现没有一个是我的情况。
在我与 Spring boot 2.0.2.RELEASE的集成测试中,我为测试创建了一个单独的 @Configuration 类,我在其中定义了 bean com.example.MyService
。这个 bean 恰好被com.example.OtherBean
.
这是代码:
测试类:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {MyIntegrationTestConfig.class},
webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public class MyService1Test extends MyAbstractServiceIntegrationTest {
@Test
public void someTest() {}
}
设置和拆卸的通用摘要:
public class MyAbstractServiceIntegrationTest{
@Before
public void setUp(){}
@After
public void tearDown()
}
src/test 中的 MyIntegrationTestConfig,用于代替 src/main 中的配置:
@Configuration
@ComponentScan({"com.example"})
public class MyIntegrationTestConfig {
@Bean
public MyService myService() {
return null;
}
}
MyService
出于测试目的,bean 可以为空。
当我运行测试时,我不断收到以下错误:
没有可用的“com.example.MyService”类型的合格 bean:预计至少有 1 个符合自动装配候选资格的 bean。依赖注释:{}
我什至尝试将这个内部类添加到 MyServic1Test。仍然没有帮助:
@TestConfiguration
static class MyServic1TestContextConfiguration {
@Bean(name = "MyService")
public MyService myService() {
return null;
}
}
知道我在这里做错了什么吗?还是我错过了什么?
我的怀疑是 Spring 会先尝试在 src/main 文件夹中创建/自动装配 bean,然后再创建在 src/test 文件夹中定义的 MyService bean。会是这样吗?或者是否存在 bean MyService 所在的不同上下文(如测试上下文),而其他 bean 存在于其他上下文中并且无法找到 MyService。
一个附带问题:对于集成测试,可以使用 webEnvironment = SpringBootTest.WebEnvironment.MOCK,对吗?
解决方案
问题是您如何初始化 bean。该值null
是导致问题的值。就好像您实际上没有声明该对象的任何实例。为了使它工作,声明一个有效的服务实例new MyService()
。
推荐阅读
- python - 有没有办法在 ANFIS 中有超过 2 个输入?
- webstorm - 如何在 WebStorm 中自定义此建议下拉菜单
- python - setMouseCallback 方法不能与 tkinter 一起使用吗?
- jmeter - JMeter 响应时间与手动计时不匹配
- php - 如何使用文件名发出 ajax GET 请求
- c# - 为什么vector3 NewPosition =(1,1,1)无效
- python-3.x - 将多个 re.sub 合二为一
- java - JAVA:如何添加两个声明的名称相同但值不同的处理值
- php - Laravel Blade @if 语句有条件地检查路由名称
- json - Spark动态Json解析成键值字符串