另一種方法可以是使用由新的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