[英]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.