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!
The @Profile(“test”) annotation is used to configure the class when the Test cases are running. Now, you can write a Unit Test case for Order Service under the src/test/resources package. The complete code for build configuration file is given below.
Spring Boot provides a @SpringBootTest annotation, which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features. The annotation works by creating the ApplicationContext used in your tests through SpringApplication .
The @SpringBootTest annotation is useful when we need to bootstrap the entire container. The annotation works by creating the ApplicationContext that will be utilized in our tests. We can use the webEnvironment attribute of @SpringBootTest to configure our runtime environment; we're using WebEnvironment.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With