log4j 如何使用junitAssertorg.slf4j.Logger语句?

of1yzvn4  于 2022-11-06  发布在  其他
关注(0)|答案(2)|浏览(122)

如何使用spring-boot-test中的junit验证来自org.slf4j.Logger的日志语句?

@Service
public class MyService {
    private final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(this.getClass());

    public void run() {
        LOGGER.info("running");
    }
}

@SpringBootTest
public class MyTest {
    @Autowired
    private MyService service;

    @Test
    public void test() {
        service.run();

        //TODO how to validate log statement?
    }
}
wa7juj8i

wa7juj8i1#

如果基础SLF4J是Log4j 2.x,正如您的标记所暗示的那样,您可以使用ListAppender,它包含在log4j-coretest-jar中。

cs7cruho

cs7cruho2#

我找到了Springs @ExtendWith(OutputCaptureExtension.class)的解决方案:

@SpringBootTest
@TestPropertySource(properties = "logging.level.root=INFO")
public class LogServiceTest {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Test
    @ExtendWith(OutputCaptureExtension.class)
    public void testLogging(CapturedOutput capture) {
        logger.info("junit"); //can be replaced with any service call that logs
        assertThat(capture.getOut()).contains("junit");
    }
}

它需要log4j配置中的follow="true"选项:
<Console name="CONSOLE" target="SYSTEM_OUT" follow="true">

相关问题