[英]Fail tests on write to System.out or .err
当测试将某些内容写入System.out或System.err时,我希望CI构建失败。 最好是,我想列出产生不需要的输出的测试列表。
我试图将Mavens surefire插件与添加的侦听器一起使用,但这仅是部分技巧,如您从JUnit RunListener在fail()上被删除的问题中可以看到的那样
有人尝试过这种方法吗?还有其他方法可以在CI版本上实现更简洁的控制台吗?
您可以看看这个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)
您可以使用Checkstyle插件,以便带有不需要的代码的测试失败,并将在surfire报告中列为失败。
您可以使用库系统规则检查测试是否将System.out
写入
public class YourTest {
@Rule
public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();
@After
public void assertNoTextHasBeenWrittenToSystemOut() {
assertEquals("", systemOutRule.getLog())
}
...
}
使用SystemErrRule
可以对System.err
进行同样的处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.