简体   繁体   中英

spring-boot: Application loads but tests fail

I am experiencing rather strange thing when using 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. However, if I try to run tests (either via launching test from IntelliJ or via surefire plugin) context fails to load.

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:

@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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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