[英]Junit not launching test case when it is an anonymous class
我正在嘗試使用JUnit進行功能測試。 基本上,我這樣做是為了訪問JUnit報告。 不幸的是,當嘗試從主要方法啟動JUnit時遇到問題。
基本上,我正在開發一種功能測試工具,用戶可以在其中從命令行提供測試文件名作為參數。 我將其簡化如下:
import org.junit.runner.JUnitCore;
public class MainClass {
public static void main(String[] args) throws Exception {
TestCase testCase = new TestCase() {
@Override
public String getPath() {
return args[0];
}
};
JUnitCore junit = new JUnitCore();
junit.run(testCase.getClass());
}
}
然后,TestCase類作用於提供的參數並提供輸出:
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestCase {
private static final Logger LOGGER = LoggerFactory.getLogger(TestCase.class);
public String getPath() {
return "etc/Default.flow";
}
@Test
public void testFunc() {
try {
LOGGER.info("Entered testFunc()");
Launcher launcher = new Launcher(getPath());
launcher.launch();
launcher.awaitCompletion();
Assert.assertTrue(launcher.getStatus());
LOGGER.info("Success");
} catch (AssertionError e) {
LOGGER.error("Assertion error", e);
}
}
因此,從上面我們可以看到,啟動器實例將以不同的文件名啟動,具體取決於在命令行上輸入的內容。
但是問題是Junit沒有運行我的匿名類。 基本上,main方法在沒有任何斷言或日志記錄的情況下退出。 因此,根本不會調用TestCase的testFunc()方法。
但是,當我將TestCase實例更改為非匿名時,一切正常,並且測試用例成功:
import org.junit.runner.JUnitCore;
public class MainClass {
public static void main(String[] args) throws Exception {
TestCase testCase = new TestCase();
JUnitCore junit = new JUnitCore();
junit.run(testCase.getClass());
}
}
為什么JUnit僅在非匿名時才啟動Test類?
如果添加偵聽器junit.addListener(new TextListener(System.out));
在運行測試之前,您會看到類似以下內容:
There were 2 failures:
1) initializationError(junit.MainClass$1)
java.lang.Exception: The class junit.MainClass$1 is not public.
...
2) initializationError(junit.MainClass$1)
java.lang.Exception: Test class should have exactly one public constructor
at org.junit.runners.BlockJUnit4ClassRunner.validateOnlyOneConstructor(BlockJUnit4ClassRunner.java:158)
at org.junit.runners.BlockJUnit4ClassRunner.validateConstructor(BlockJUnit4ClassRunner.java:147)
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:127)
at org.junit.runners.ParentRunner.validate(ParentRunner.java:416)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:84)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:65)
這意味着JUnit無法執行由匿名類表示的測試用例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.