How to test main class of Spring-boot application

后端 未结 9 1883
心在旅途
心在旅途 2020-12-03 00:18

I have a spring-boot application where my @SpringBootApplication starter class looks like a standard one. So I created many tests for all my functi

9条回答
  •  执念已碎
    2020-12-03 01:15

    I had the same goal (having a test that runs the main() method) and I noticed that simply adding a test method like @fg78nc said will in fact "start" the application twice : once by spring boot test framework, once via the explicit invocation of mainApp.main(new String[] {}), which I don't find elegant.

    I ended up writing two test classes : one with @SpringBootTest annotation and the empty test method applicationContextLoaded(), another one without @SpringBootTest (only RunWith(SpringRunner.class)) that calls the main method.

    SpringBootApplicationTest

    package example;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.boot.test.context.SpringBootTest;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class SpringBootApplicationTest {
    
      @Test
      public void contextLoads() {
      }
    }
    

    ApplicationStartTest

    package example;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.test.context.junit4.SpringRunner;
    
    @RunWith(SpringRunner.class)
    public class ApplicationStartTest {
      @Test
      public void applicationStarts() {
        ExampleApplication.main(new String[] {});
      }
    }
    

    Overall, the application is still started two times, but because there is now two test classes. Of course, with only these two tests methods, it seems overkill, but usually more tests will be added to the class SpringBootApplicationTest taking advantage of @SpringBootTest setup.

提交回复
热议问题