[英]Running a JUnit4 test - from a java program
I was wondering how to run some JUnit4 test inside a java program. 我想知道如何在Java程序中运行一些JUnit4测试。 Basically - depending on some conditions during runtime I need to decide which test runner to use. 基本上-根据运行时的某些条件,我需要确定要使用哪个测试运行程序。 Using Junit3 I could override runTest method from TestCase class - but in JUnit4 tests do not extend TestCase class so I have nothing to override... Is there maybe some method that I need to implement... or sth else... 使用Junit3可以覆盖TestCase类的runTest方法-但是在JUnit4测试中,不扩展TestCase类,因此我没有什么要覆盖的。也许我需要实现某些方法...或其他...
The problem I have is that I have to run a method (which cannot be static) before each test case 我的问题是我必须在每个测试用例之前运行一个方法(不能是静态的)
If this non-static method is something related to pre-conditioning the test case, you could achieve this by annotating a method using @Before
in you test class. 如果此非静态方法与预处理测试用例有关,则可以通过在测试类中使用@Before
注释方法来实现此@Before
。 Take a look at the Junit4 docs for the behavior of @Before
. 看看Junit4文档中@Before
的行为。
Otherwise, to simply trigger a Junit test class, you can use the following code: 否则,只需触发Junit测试类,就可以使用以下代码:
Runner r =
try {
r = new BlockJUnit4ClassRunner(Class.forName(testClass));
} catch (ClassNotFoundException | InitializationError e) { // FIX if necessary: JDK 7 syntax
// handle
}
JUnitCore c = new JUnitCore();
c.run(Request.runner(r));
Hope that helps. 希望能有所帮助。
Here's some sample code for you: 以下是一些示例代码:
public void checkTests() throws org.junit.runners.model.InitializationError {
checkTestClass((Class<?>) MyTestClss.class);
}
private void checkTestClass(Class<?> theClass) throws InitializationError {
final RunNotifier notifier = new RunNotifier();
notifier.addListener(new RunListener() {
@Override
public void testFailure(Failure failure) throws Exception {
Assert.fail(failure.getMessage());
}
});
final Runner runner = new BlockJUnit4ClassRunner(theClass);
runner.run(notifier);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.