Apologize as this might seems to be an useless act, but is there any way we can actually do junit test on Spring-Boot(1.3.8.RELEASE)'s Application.java which this class does nothing but to start a Spring-boot application?
Given below:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
try{
SpringApplication.run(Application.class, args);
}catch(Exception e){
//code here
}
}
}
Maybe i can try catching exception? but what else can i possibly test so that JUnit will test out SpringApplication.run()? any example is appreciated. Thank you all!
Usually, the following is sufficient to test that the application context starts up.
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class ApplicationTests {
@Test
public void contextLoads() {
}
}
However, if you want to directly test Application.main
, you can also test it this way:
public class ApplicationTest {
@Test
public void test()
{
Application.main(new String[]{
"--spring.main.web-environment=false",
"--spring.autoconfigure.exclude=blahblahblah",
// Override any other environment properties according to your needs
});
}
}
Maybe i can try catching exception? but what else can i possibly test
so that JUnit will test out SpringApplication.run()? any example is
appreciated. Thank you all!
Making the test fail if an exception is caught is here helpless as a thrown exception during a test has already as consequence to make the test fail (in error more precisely).
If you execute already test classes that load the whole spring boot context (@SpringBootTest
) you don't need to write a test to check that it is correctly loaded.
You should test the Application
class if it has some logic.
For example you could declare a method annotated with @Before
that does some processing after the context is loaded and you would like to assert that the processing is done as it should done. Other example : you could pass some arguments in the main()
method and you would like to assert that the arguments are used by the method as expected.
All that is testable with @SpringBootTest
.
If your Application
class does nothing but :
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
but you need all the same to cover the main()
test method to be compliant with some coverage tool or organization, create an integration test for that, document it clearly and let the integration continuous does that because loading a Spring Boot application takes time. You can refer to this question.