How to test main class of Spring-boot application

后端 未结 9 1882
心在旅途
心在旅途 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:11

    In addition to the answers above, here is a unit test of a SpringBoot application's main method for if you are using JUnit 5:

    try (MockedStatic mocked = mockStatic(SpringApplication.class)) {
                
       mocked.when(() -> { SpringApplication.run(ElectronicGiftCardServiceApplication.class, 
          new String[] { "foo", "bar" }); })
             .thenReturn(Mockito.mock(ConfigurableApplicationContext.class));
                
       ElectronicGiftCardServiceApplication.main(new String[] { "foo", "bar" });
                
       mocked.verify(() -> { SpringApplication.run(ElectronicGiftCardServiceApplication.class, 
          new String[] { "foo", "bar" }); });
    
    }   
    

    It verifies that the static method run() on the SpringApplication class is called with the expected String array when we call ElectronicGiftCardServiceApplication.main().

    Same idea as awgtek and Ramji Sridaran, but their solutions are for JUnit 4.

提交回复
热议问题