2

How to Unit test Spring-Boot Application main() method with SpringApplication.run() . I am wondering if it is possible to get Jacoco test coverage on this class. (Otherwise I will exclude it)

This question is similar, but not the same, as this question: Spring Boot, test main application class

I am using mockito-core 3.8 and mockito-inline.

This test code works for me but Jacoco does not pick it up as test coverage:

@SpringBootTest
@ActiveProfiles("test")
public class AutowireTest {

    private static final String ARG = "";
    private static final String[] ARGS = new String[]{ARG};

    @Autowired
    ConfigurableApplicationContext context;

    @Test
    public void main() {
        try (MockedStatic<Application> appStatic = Mockito.mockStatic(Application.class);
             MockedStatic<SpringApplication> springStatic = Mockito.mockStatic(
               SpringApplication.class)) {
            appStatic.when(() -> Application.main(ARGS))
                .thenCallRealMethod();
            springStatic.when(() -> SpringApplication.run(Application.class, ARGS))
                .thenReturn(context);

            // when
            Application.main(ARGS);

            //then
            appStatic.verify(times(1),
                () -> Application.main(ARGS));
            springStatic.verify(times(1),
                () -> SpringApplication.run(Application.class, ARGS));
        }
    }
}

Is Jacoco not able to show coverage on static methods?

djangofan
  • 28,471
  • 61
  • 196
  • 289
  • 1
    Does this answer your question? [How to test main class of Spring-boot application](https://stackoverflow.com/questions/46650268/how-to-test-main-class-of-spring-boot-application) – xerx593 Feb 26 '21 at 22:29
  • No, doesn't answer it but it does provide one answer that might be a workaround I can use, by using the Generated Lombok annotation to exclude the code scan. – djangofan Feb 27 '21 at 17:19
  • Also interested by how to achieve this with Mockito (not Lombok, not having to start the server) – PatPanda Mar 01 '21 at 01:59
  • I don't understand. The above example in my question is already using Mockito with Mockito.mockStatic – djangofan Mar 04 '21 at 01:41

0 Answers0