Java 使用实例而不是类运行JUnitCore
我希望以编程方式运行JUnit 4.12+,在许多其他类似的帖子中,我粗略地搜索了一下,其中规定了以下基本解决方案:Java 使用实例而不是类运行JUnitCore,java,junit4,Java,Junit4,我希望以编程方式运行JUnit 4.12+,在许多其他类似的帖子中,我粗略地搜索了一下,其中规定了以下基本解决方案: @RunWith(Suite) @Suite.SuiteClasses ({ MyTestClass1.class, MyTestClass2.class }) public class MyTestSuite { } Result testResults = JUnitCore.runClasses(MyTestSuite.class); …我能让这一切顺利
@RunWith(Suite)
@Suite.SuiteClasses ({
MyTestClass1.class,
MyTestClass2.class
})
public class MyTestSuite {
}
Result testResults = JUnitCore.runClasses(MyTestSuite.class);
…我能让这一切顺利进行,不费吹灰之力。到目前为止还不错
问题是:我有一些非常复杂的测试类,需要在运行时实例化/注入非常特定的属性…而不是从无参数构造函数内部完成的事情。但是上面指定只运行一组类的任何旧实例的方法不允许您实例化测试类,配置它们,然后运行它们
有办法做到这一点吗?我在这张照片上找不到任何东西。我正在寻找类似于:
MyTestClass1 mtc1 = new MyTestClass1(...);
MyTestClass2 mtc2 = new MyTestClass2(...);
Result testResults = JUnitCore.run(mtc1, mtc2);
您可能需要定制runner来实现这一点。JUnit4/5附带了第三方运行程序,可以为构造函数和方法执行依赖项注入。在使用Spring的情况下,很少有非常流行的runner是MockitoMockitoJUnitRunner和SpringJUnit4ClassRunner。您可以在以下位置查看自定义运行程序和实现详细信息:
我通过使用示例Groovy伪代码的自定义运行程序实现了这一点,如下所示:
class MyRunner extends Runner {
@Override
Description getDescription() {
return null
}
@Override
void run(RunNotifier notifier) {
// LoginTests.class is a test class I want to run
LoginTests loginTests = new LoginTests(<my args here>)
Description description = Description.createSuiteDescription(LoginTests)
notifier.fireTestStarted(description)
try {
log.info("About to doSomething()...")
loginTests.doSomething()
log.info("Did it...")
notifier.fireTestFinished(description)
} catch(Throwable throwable) {
log.info("doSomething() failed...")
notifier.fireTestAssumptionFailed(new Failure(description, throwable))
}
}
}
Result testResults = new JUnitCore().run(Request.runner(new MyRunner()))
谢谢@user8185075+1-您是在谈论公共结果runner吗?我是在谈论ParameterResolver[。它为测试扩展定义API,以便在运行时动态解析参数。