Thursday, November 20, 2014

Spring Boot and JUnit

New gig is ramping up the use of Spring Boot. Absolutely love it. New gig is also committed to the idea of micro-services. There's pros and cons with that one. Moving on... Start with an example like this: 

https://spring.io/guides/gs/accessing-data-rest/ 

And we can temporarily store some rest/json data in a quick spring boot app with a quick maven command: 

mvn spring-boot:run

The trick is that if you want to run a j-unit test against this new web service, how do you identify it?  Should it spawn a new thread?  Should the test have a static dependency somewhere else in the test harness?

With a soup of annotations, you get the right way to do this unit test:

http://www.jayway.com/2014/07/04/integration-testing-a-spring-boot-application

But here's the thing about the above blog post.  It won't work.

It's missing a critical static pair of methods:


private static ConfigurableApplicationContext appContext;
    
@BeforeClass
public static void startBootApp(){
    appContext = SpringApplication.run(MockDataApplication.class, "");
}
    
@AfterClass
public static void shutdownBootApp(){
    appContext.close();

}


You have to do execute these statically.  You only want one spring boot application running before the unit test runs.  If you use @Before annotation, you'll get a new app launched before every @Test block.  

So that's it.  It's pretty sweet.  You load up the JPA repository with data, then you run tests against that web service, checking for the data.  Plus the RestAsssured library has a very slick json validation format. 

Work in progress of a test project can be found here:

https://github.com/bgardella/spring-boot-example








1 comment: