[英]spring-boot: Application loads but tests fail
I am experiencing rather strange thing when using Spring Boot. 使用Spring Boot时,我遇到了相当奇怪的事情。 Lets get with it. 让我们开始吧。 I have an app which, when ran from spring-boot:run, loads perfectly fine and I can use my server. 我有一个应用程序,当从spring-boot:run运行时,可以很好地加载,并且可以使用我的服务器。 However, if I try to run tests (either via launching test from IntelliJ or via surefire plugin) context fails to load. 但是,如果我尝试运行测试(通过从IntelliJ启动测试或通过surefire插件),则无法加载上下文。
Issue lies within this class (only relevant part shown): 问题在于此类(仅显示相关部分):
@RestController
@RequestMapping(
value = "/sa/revisions/"
)
@SuppressWarnings("unchecked")
class RevisionController {
@Autowired
// cant autowire this field
private RepositoryEntityLinks repositoryEntityLinks = null;
/* omitted */
}
And here is my main class: 这是我的主要课程:
@EnableAsync
@EnableCaching
@EnableAutoConfiguration
@EnableConfigurationProperties
@Import({
SecurityConfiguration.class,
DataConfiguration.class,
RestConfiguration.class
})
public class SpringAtomApplication {
@Autowired
private DataLoaderManager dataLoaderManager = null;
public static void main(String[] args) {
SpringApplication.run(SpringAtomApplication.class, args);
}
@Bean
public CacheManager cacheManager() {
final GuavaCacheManager manager = new GuavaCacheManager();
manager.setAllowNullValues(false);
return manager;
}
@PostConstruct
private void doPostConstruct() {
this.dataLoaderManager.doLoad();
}
}
As I said, application loads without an issue when ran normally, however when it comes to this simple test, everything falls apart: 就像我说的那样,正常运行时应用程序加载没有问题,但是,就这个简单的测试而言,一切都崩溃了:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringAtomApplication.class)
public class SpringAtomApplicationTests {
@Test
public void contextLoads() {
}
}
Would appreciate any suggestion, because I'd love to start with testing it. 将不胜感激任何建议,因为我很乐意从测试开始。
You should set SpringApplicationContextLoader
in your test class: 您应该在测试类中设置SpringApplicationContextLoader
:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(
classes = SpringAtomApplication.class,
loader = SpringApplicationContextLoader.class)
public class SpringAtomApplicationTests {
@Test
public void contextLoads() {
}
}
With that you can test non-web features (like a repository or a service) or start an fully-configured embedded servlet container and run your tests using MockMvc. 这样一来,您可以测试非Web功能(例如存储库或服务),或启动完全配置的嵌入式Servlet容器,并使用MockMvc运行测试。
Reference: http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/SpringApplicationContextLoader.html 参考: http : //docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/SpringApplicationContextLoader.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.