![](/img/trans.png)
[英]How to AutoWire spring beans when using Mockito and Junit?
[英]How to autowire beans in test class when using @SpringBootTest
我有一个使用@SpringBootTest
注释的集成测试类,它启动完整的应用程序上下文并让我执行我的测试。 但是我无法将@Autowired
bean放入测试类本身。 相反,我得到一个错误:
没有'my.package.MyHelper'类型的限定bean可用“。
如果我没有@Autowire我的助手类,但将代码直接保存在setUp函数中,测试按预期工作。
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Application.class)
public class CacheControlTest {
@Autowired
private MyHelper myHelper;
@Before
public void setUp() {
myHelper.doSomeStuff();
}
@Test
public void test1() {
// My test
}
}
如何在使用@SpringBootTest
同时在测试类中使用Spring自动@SpringBootTest
?
按照下面的@ user7294900建议,创建一个单独的@Configuration
文件并在CacheControlTest顶部添加它:
@ContextConfiguration(classes = { CacheControlTestConfiguration.class })
但有没有办法将配置保留在CacheControlTest
类本身? 我已经尝试在我的测试类中添加:
public class CacheControlTest {
@TestConfiguration
static class CacheControlTestConfiguration {
@Bean
public MyHelper myHelper() {
return new MyHelper();
}
}
}
和
public class CacheControlTest {
@Configuration
static class CacheControlTestConfiguration {
@Bean
public MyHelper myHelper() {
return new MyHelper();
}
}
}
但它们似乎没有任何影响。 我仍然得到同样的错误。 如上所述,当放置在单独的文件中时,相同的配置块也可以工作。
为您的测试类添加ContextConfiguration:
@ContextConfiguration(classes = { CacheControlTestConfiguration.class })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.