Byt*_*yte 9 java testing logging junit-rule junit5
I am transitioning from junit4 to junit5 on a project and trying to figure out how to test logs. Previously, I used
@Rule
OutputCapture outputCapture = new OutputCapture();
Run Code Online (Sandbox Code Playgroud)
and would then write an assertion using outputCapture.toString()
, for example
assertThat(outputCapture.toString(),containsString("status=200"));
Since @Rule
annotation hasn't been implemented yet in junit5, I can't use outputCapture. Any ideas what to do instead? Thanks!
Vai*_*ibS 19
有一个扩展提供了相同的功能,您可以按如下方式使用它:
@ExtendWith(OutputCaptureExtension.class)
public class MyTestClass {
@Test
void myTestCase(CapturedOutput capturedOutput) {
assertTrue(capturedOutput.getOut().contains("expected string"));
assertTrue(capturedOutput.getErr().contains("expected string"));
}
}
Run Code Online (Sandbox Code Playgroud)
我们在 JUnit5 迁移期间偶然发现了同样的问题。经过一番研究,我找到了一个技术解决方案,但似乎还没有人用它制作测试库。所以这就是我所做的。它已发布到 Maven Central,因此您可以立即使用它:
https://github.com/netmikey/logunit
您可以按如下方式使用它:
public class MyModuleTest {
@RegisterExtension
LogCapturer logs = LogCapturer.create().captureForType(MyModule.class);
@Test
public void testLogging() {
// ... do the testing ...
// Run assertions on the logged messages
logs.assertContains("Some message");
}
}
Run Code Online (Sandbox Code Playgroud)
(更多示例请参见项目的README)
@Rule
并且@ClassRule
不再存在;取代@ExtendWith
; 有关部分规则支持,请参阅以下部分。
为了使用JUnit 4 的现有@Rule
支持,建议使用一种方法或类级别注释的方法。
与 JUnit 4 一样,支持规则注释字段和方法。通过在测试类上使用这些类级扩展,遗留代码库中的此类规则实现可以保持不变,包括 JUnit 4 规则导入语句。
这种有限形式的规则支持可以通过类级别注释来打开
org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport
更好的选择仍然是重新设计您的测试套件,以使用JUnit5 的扩展模型(如果您正在使用它)。