当测试向System.out或System.err写入内容时,我希望CI构建失败。最好我想列出一些产生不必要输出的测试。写入System.out或.err失败测试
我试图用内行保命插件与添加的监听器,但也不只是伎俩的一部分,你可以从这个问题看JUnit RunListener is removed on fail()
是不是有人尝试这样的事情以及是否有其他方式来实现CI构建一个更清洁的控制台?
当测试向System.out或System.err写入内容时,我希望CI构建失败。最好我想列出一些产生不必要输出的测试。写入System.out或.err失败测试
我试图用内行保命插件与添加的监听器,但也不只是伎俩的一部分,你可以从这个问题看JUnit RunListener is removed on fail()
是不是有人尝试这样的事情以及是否有其他方式来实现CI构建一个更清洁的控制台?
您可以使用Checkstyle插件,以便您使用不需要的代码进行测试失败,并将在surfire报告中列为失败。
你可能会看看这个Maven插件https://github.com/policeman-tools/forbidden-apis
,它检查禁止的API调用。你可以定义在代码中应该禁止的唯一呼叫。
编辑简单示例显示排除不允许的API调用。在这个例子中,除了一个测试类以外,测试类中不允许调用System.out.println
。
pom.xml
<build>
<plugins>
<plugin>
<groupId>de.thetaphi</groupId>
<artifactId>forbiddenapis</artifactId>
<version>2.0</version>
<executions>
<execution>
<goals>
<goal>check</goal>
<goal>testCheck</goal>
</goals>
</execution>
</executions>
<configuration>
<signaturesFiles>
<signaturesFile>${project.build.testOutputDirectory}/signatures.txt</signaturesFile>
</signaturesFiles>
<excludes>
<!-- specify the classes which should be excluded -->
<exclude>**/Permitted*</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
的签字:文件src\test\resources\signatures.txt
java.io.PrintStream#println(java.lang.String)
测试类
// the one which doesn't use System.out
package sub.optimal;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Assert;
import org.junit.Test;
public class NoSystemOutTest {
@Test
public void dummy() {
Logger logger = Logger.getGlobal();
logger.log(Level.INFO, "some info");
Assert.assertTrue(true);
}
}
。
// the one in which the use of System.out should be permitted
package sub.optimal;
import org.junit.Assert;
import org.junit.Test;
public class PermittedSystemOutTest {
@Test
public void dummy() {
System.out.println("permitted usage");
Assert.assertTrue(true);
}
}
。
// the one in which the use of System.out is not permitted
package sub.optimal;
import org.junit.Assert;
import org.junit.Test;
public class NotPermittedSystemOutTest {
@Test
public void dummy() {
System.out.println("not permitted usage");
Assert.assertTrue(true);
}
}
运行与mvn test-compile forbiddenapis:testCheck
支票只能在NotPermittedSystemOutTest
报告被禁止的API使用。
[ERROR] Forbidden method invocation: java.io.PrintStream#println(java.lang.String)
[ERROR] in sub.optimal.NotPermittedSystemOutTest (NotPermittedSystemOutTest.java:9)
我是全球变暖的同事。我们的问题是,有一些有效的情况下调用'System.out' /'.err'是一个有效的情况。 – user3001
@ user3001请检查添加的示例如何从支票中排除班级。 – SubOptimal
可以检查测试是否通过使用图书馆System Rules
public class YourTest {
@Rule
public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();
@After
public void assertNoTextHasBeenWrittenToSystemOut() {
assertEquals("", systemOutRule.getLog())
}
...
}
有相同的可System.err
使用SystemErrRule
来完成写入System.out
。
需要您的帮助[**链接**](https://stackoverflow.com/questions/46712632/systemoutrule-in-junit-test-didnt-capture-standard-output):) – Woland
我们的项目中有部分使用System.out.print,这没关系。这只是为了保持'mvn测试'输出清洁。 – globalworming