Java 弹簧启动测试-没有类型为'的合格bean;com.example.MyService';可获得的
关于stackoverflow有很多类似的问题,但我发现没有一个是我的问题 在我与Spring boot2.0.2.RELEASE的集成测试中,我为测试创建了一个单独的@Configuration类,在这里我定义了beanJava 弹簧启动测试-没有类型为'的合格bean;com.example.MyService';可获得的,java,spring,spring-boot,spring-boot-test,Java,Spring,Spring Boot,Spring Boot Test,关于stackoverflow有很多类似的问题,但我发现没有一个是我的问题 在我与Spring boot2.0.2.RELEASE的集成测试中,我为测试创建了一个单独的@Configuration类,在这里我定义了beancom.example.MyService。这个bean恰好被com.example.OtherBean中的其他bean使用 代码如下: 测试等级: @RunWith(SpringRunner.class) @SpringBootTest(classes = {MyIntegr
com.example.MyService
。这个bean恰好被com.example.OtherBean
中的其他bean使用
代码如下:
测试等级:
@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个符合autowire候选条件的bean。依赖项批注:{}
我甚至尝试将这个内部类添加到MyService1Test中。仍然没有帮助:
@TestConfiguration
static class MyServic1TestContextConfiguration {
@Bean(name = "MyService")
public MyService myService() {
return null;
}
}
知道我做错了什么吗?还是我错过了什么
我怀疑Spring在创建src/test文件夹中定义的MyService bean之前,首先尝试在src/main文件夹中创建/autowire bean。是这样吗?或者是否存在一个不同的上下文(比如测试上下文),其中bean MyService位于其中,而其他bean位于另一个上下文中,并且无法定位MyService
附带问题:对于集成测试,可以使用webEnvironment=SpringBootTest.webEnvironment.MOCK,对吗 问题在于如何初始化bean。值
null
是导致问题的值。这就好像您实际上没有声明该对象的任何实例一样。要使其工作,请声明服务的有效实例new MyService()
尝试返回new MyService()
而不是null
,以检查错误是否仍然存在。哈哈,@NiVeR。这个错误似乎消失了。现在我要面对一堆豆子去做那样的事。问题:我可以在@Configuration MyIntegrationTestConfig类中使用@MockBean吗?我试过了,看起来还可以,但不确定在配置类中这样做是否正确。所以,也许最后一个问题是,为什么SpringBoot将null视为无bean?刚刚搜索,没有找到任何相关的文档。对于最后一个问题,有一个很好的答案:。@Simo你的问题包含一些很好的代码+1.