如何使用org.slf4j.Logger中的junit验证spring-boot-test中的日志语句
@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?
}
}发布于 2022-09-01 08:31:19
我用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");
}
}它需要在您的follow="true"配置中使用log4j选项:
<Console name="CONSOLE" target="SYSTEM_OUT" follow="true">
发布于 2022-03-09 18:53:58
如果底层的SLF4J是Log4j 2.x,就像标记可能包含的那样,您可以使用ListAppender,它包含在log4j-core的test-jar中。
https://stackoverflow.com/questions/71397516
复制相似问题