繁体   English   中英

春季启动:应用程序加载但测试失败

[英]spring-boot: Application loads but tests fail

使用Spring Boot时,我遇到了相当奇怪的事情。 让我们开始吧。 我有一个应用程序,当从spring-boot:run运行时,可以很好地加载,并且可以使用我的服务器。 但是,如果我尝试运行测试(通过从IntelliJ启动测试或通过surefire插件),则无法加载上下文。

问题在于此类(仅显示相关部分):

@RestController
@RequestMapping(
  value = "/sa/revisions/"
)
@SuppressWarnings("unchecked")
class RevisionController {
  @Autowired
  // cant autowire this field
  private RepositoryEntityLinks   repositoryEntityLinks = null;
  /* omitted */
}

这是我的主要课程:

@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();
  }
}

就像我说的那样,正常运行时应用程序加载没有问题,但是,就这个简单的测试而言,一切都崩溃了:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringAtomApplication.class)
public class SpringAtomApplicationTests {
  @Test
  public void contextLoads() {
  }
}

将不胜感激任何建议,因为我很乐意从测试开始。

您应该在测试类中设置SpringApplicationContextLoader

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(
    classes = SpringAtomApplication.class, 
    loader = SpringApplicationContextLoader.class)
public class SpringAtomApplicationTests {
  @Test
  public void contextLoads() {
  }
}

这样一来,您可以测试非Web功能(例如存储库或服务),或启动完全配置的嵌入式Servlet容器,并使用MockMvc运行测试。

参考: http : //docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/SpringApplicationContextLoader.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM