System.out.print()在测试方法中没有显示任何内容

我正在尝试使用System.out在我的unit testing中打印一些数据( @Test mehotds),但它没有显示任何内容。 但是,它在@Before方法中正常工作。 我正在使用JUnit和Maven Surefire插件。

 public class MyTests { @Before void init(){ System.out.println("Initializing some data..."); // <- It works. } @Test void shouldRemoveSeries() { System.out.println("TEST: Should remove series"); // <- It doesn't. } } 

maven-surefire-plugin配置:

  org.apache.maven.plugins maven-surefire-plugin 2.15   **/*Tests.java    

谢谢。

使用日志

 private static Logger log = Logger.getLogger(LoggingObject.class); log.info("I'm starting"); 

或System.setOut()

 private final PrintStream stdout = System.out; private final ByteArrayOutputStream output = new ByteArrayOutputStream(); private TerminalView terminalview; 

也进入这个。 我正在使用gradle来管理我的任务,我将它放在build.gradle文件的末尾:

 test { testLogging.showStandardStreams = true } 

现在我看到System.out.println(whateves)

要通过System.out.println获取编写的测试的输出,您需要配置maven-surefire-plugin将此输出重定向到一个文件,该文件可以通过使用以下方法实现:

  org.apache.maven.plugins maven-surefire-plugin 2.18.1  true   

选项redirectTestOutputToFile会将System.out.println等的输出重定向到单独创建的文件中:

摘自文档:

将其设置为“true”以将unit testing标准输出重定向到文件(在reportsDirectory / testName-output.txt中找到)。

除此之外,System.out.println在一般的unit testing中没有意义。

问题是测试类的名称。 要在构建中的测试阶段(通过Maven surefire插件)进行识别,必须将其命名为“* Test”:

包含和排除测试

我在单独的非测试课上做了一个小技巧。 它不像logger那么顺利,但是如果你在Spring Boot中寻找快速解决方案,你可以使用它。

PrintForTest.java

 import org.springframework.stereotype.Controller; @Controller public class PrintForTest { public static void print(String input){ System.out.println(input); } } 

MainTest.java

 import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.junit.Assert; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @SpringBootTest @RunWith(SpringRunner.class) public class MainTest { ... @Test public void testingSomething(){ PrintForTest.print("My new System.out.print()"); Assert.assertEquals(...); } } 

编辑:使用静态方法,无需使用@Autowired。

这听起来很熟悉,所以我假设你从某些IDE(Netbeans?)运行你的测试。 可能是它只显示失败的测试的输出。 从控制台运行测试时是否也会出现这种情况?

使用System.err而不是System.out可能会有更多的运气,但我不确定这一点。