2021-12-10

Tech Programing

程式人小天地

Test Spring boot Application startup using Junit

1 min read


I have some business logic that runs when Spring boot application starts (i.e in main method)

@SpringBootApplication
@EnableGatewayService
@EnableAsync
@Slf4j
public class AuthOpsApplication {
     public static void main(String[] args) throws IOException {
        application.addListeners(new WEPFallbackListener());
        application.addListeners(new SaeListener());
        application.run(args);
        // some business logic
        log.info("logs some info of the business logic");

    }
}

I want to write a test case to check if the log.info is getting printed and its value is as expected. I do not want to test the business logic as a standalone code, I would like to run the main function and somehow read the log that it puts out, Is this possible?

What I tried:

import org.springframework.test.context.junit4.SpringRunner;
import uk.org.lidalia.slf4jtest.TestLogger;
import uk.org.lidalia.slf4jtest.TestLoggerFactory;
import org.springframework.boot.test.autoconfigure.actuate.metrics.AutoConfigureMetrics;
import org.springframework.test.context.ActiveProfiles;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = AuthOpsApplication.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.ANY)
@ActiveProfiles("test")
@AutoConfigureMetrics
public class LogTest {
    TestLogger logger = TestLoggerFactory.getTestLogger(AuthOpsApplication.class);


    @Test
    public void testAnyLog() throws IOException {
        System.out.println(logger.getLoggingEvents());

    }

    @After
    public void clearLoggers() {
        TestLoggerFactory.clear();
    }
}

This runs successfully and creates all the Beans but does not actually call the main() method of my AuthOpsApplication class.

( I can say this because the System.out.println() that I did gives all the other logs except the ones in main() method).

Thanks in advance for the help.



Source link

資料來源:Stackoverflow

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *