Spring boot test configuration

sansari picture sansari · Jul 20, 2016 · Viewed 75.8k times · Source

I have a spring boot application with main class like below:

@SpringBootApplication
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}

Now I want to test my services and created a base test class:

@SpringApplicationConfiguration(Application.class)
public abstract class TestBase {
}

When I run my test I get exception:

Caused by: java.lang.IllegalArgumentException: Can not load an ApplicationContext with a NULL 'contextLoader'. Consider annotating your test class with @ContextConfiguration.
    at org.springframework.util.Assert.notNull(Assert.java:115)
    at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:117)
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:148)

Then I change my base test class using ContextConfiguration

@ContextConfiguration(classes = Application.class)
public abstract class TestBase {
}

This time I get DataSource initialization error. I am wondering why it is failing in first case and why in second case it does not load my application.properties where I have configured datasource.

Thank you!

Answer

Mike3355 picture Mike3355 · Nov 4, 2016

Something like that:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class ApplicationTest{

   @Autowired
   Foo foo; //whatever you are testing

   @Test
   public void FooTest() throws Exception{
     Foo f = foo.getFooById("22");
     assertEquals("9B", f.getCode); 
   }
 //TODO look into MockMVC for testing services
}