如何在junit5中测试日志记录?

时间:2017-03-13 14:24:48

标签: java testing logging junit-rule junit5

我正在从项目的junit4过渡到junit5并试图弄清楚如何测试日志。以前,我用过

@Rule
OutputCapture outputCapture = new OutputCapture();

然后使用outputCapture.toString()编写断言,例如

assertThat(outputCapture.toString(),containsString("status=200"));

由于@Rule注释尚未在junit5中实现,因此我无法使用outputCapture。任何想法该怎么做?谢谢!

4 个答案:

答案 0 :(得分:2)

Migration Tip中的JUnit5 documentation明确指出 -

  

@Rule@ClassRule不再存在;被@ExtendWith取代;请参阅以下部分以获取部分规则支持。

为了使用existing @Rule support from JUnit 4,有一种建议用于方法或类级别注释的方法。

  

与JUnit 4一样,支持带有规则注释的字段以及方法。   通过在测试类上使用这些类级扩展,例如Rule   遗留代码库中的实现可以保持不变,包括   JUnit 4规则导入语句。

     

这种有限形式的规则支持可以通过以下方式启用   类级注释   org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport

如果您正在使用Extension Model from JUnit5,更好的选择仍然是重新设计测试套件以使用{{3}}。

答案 1 :(得分:2)

提供了相同的扩展程序,您可以按如下方式使用它:

@ExtendWith(OutputCaptureExtension.class)
public class MyTestClass {

    @Test
    void myTestCase(CapturedOutput capturedOutput) {
        assertTrue(capturedOutput.getOut().contains("expected string"));
        assertTrue(capturedOutput.getErr().contains("expected string"));
    }
}

答案 2 :(得分:0)

我们在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");
    }
}

(有关更多示例,请参见项目的README

答案 3 :(得分:0)

您还可以通过快速自行实施以下解决方案来轻松测试写入 System.out 的日志输出:

// Configure System.out to be written to a buffer from which we can read
PrintStream realSysOut = System.out;
BufferedOutputStream sysOutBuffer = new ByteArrayOutputStream();
System.setOut(new PrintStream(sysOutBuffer));
...
// Perform some action which logs something to System.out
System.out.println("Some random content written to System.out");
...
// Assert that a given string was written in the meantime to System.out
assertThat(new String(buffer.toByteArray()), containsString("random content"));
...
// Don't forget to bring back the real System.out at the end of the test
System.setOut(realSysOut);

在检查写入System.err的日志输出的情况下,可以等效地通过用 System.setErr(...)替换 System.setOut(...)来实现它 System.out System.err 在上面的示例中。

相关问题