另一种方法可以是使用由新的JUnit 5提供的设施 - 木星框架。
我把我与Java 1.8 Eclipse的氧气测试下面的代码。代码缺乏优雅和简洁,但可以作为构建元测试用例的强大解决方案的基础。
注意,这实际上是JUnit的5是如何测试时,我是指你the unit tests of the Jupiter engine on Github。
public final class DisallowUppercaseLetterAtBeginningTest {
@Test
void testIt() {
// Warning here: I checked the test container created below will
// execute on the same thread as used for this test. We should remain
// careful though, as the map used here is not thread-safe.
final Map<String, TestExecutionResult> events = new HashMap<>();
EngineExecutionListener listener = new EngineExecutionListener() {
@Override
public void executionFinished(TestDescriptor descriptor, TestExecutionResult result) {
if (descriptor.isTest()) {
events.put(descriptor.getDisplayName(), result);
}
// skip class and container reports
}
@Override
public void reportingEntryPublished(TestDescriptor testDescriptor, ReportEntry entry) {}
@Override
public void executionStarted(TestDescriptor testDescriptor) {}
@Override
public void executionSkipped(TestDescriptor testDescriptor, String reason) {}
@Override
public void dynamicTestRegistered(TestDescriptor testDescriptor) {}
};
// Build our test container and use Jupiter fluent API to launch our test. The following static imports are assumed:
//
// import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass
// import static org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder.request
JupiterTestEngine engine = new JupiterTestEngine();
LauncherDiscoveryRequest request = request().selectors(selectClass(MyTest.class)).build();
TestDescriptor td = engine.discover(request, UniqueId.forEngine(engine.getId()));
engine.execute(new ExecutionRequest(td, listener, request.getConfigurationParameters()));
// Bunch of verbose assertions, should be refactored and simplified in real code.
assertEquals(new HashSet<>(asList("validTest()", "TestShouldNotBeCalled()")), events.keySet());
assertEquals(Status.SUCCESSFUL, events.get("validTest()").getStatus());
assertEquals(Status.FAILED, events.get("TestShouldNotBeCalled()").getStatus());
Throwable t = events.get("TestShouldNotBeCalled()").getThrowable().get();
assertEquals(RuntimeException.class, t.getClass());
assertEquals("test method names should start with lowercase.", t.getMessage());
}
虽然有点冗长,这种方法的一个优点是它不需要嘲讽,并在同一JUnit的容器执行测试,稍后会为真正的单元测试中使用。
随着位的清理,更加可读代码是可以实现的。同样,JUnit-Jupiter资源可以成为一个很好的灵感来源。
此扩展只是一个示例,真正的扩展是特定于域的。我的问题是更多关于如何测试我的扩展。 –
我在https://stackoverflow.com/questions/46841243/how-to-test-extension-implementations中提出了一个类似的问题,我希望很快就会有一个测试工具用于扩展。 – mkobit