據我的理解,可以有從ExternalResource
到JUnit5中的等效項之間沒有一對一映射。這些概念不適合。在JUnit4中,ExternalResource
基本上給你一個before
和一個after
回調,但在規則中,你不能控制before
和after
的實際含義。您可以將它與@Rule
或@ClassRule
一起使用。
在JUnit5,延伸被定義在特定extension points並且因此「何時」被很好地定義鉤。
在概念的另一個區別是,你可以在JUnit4規則的狀態,但你的JUnit5擴展不應該有任何的狀態。相反,所有州應該去execution context。
儘管如此,這裏是我走過來一個選項,其中before
和after
涉及到每個測試方法:
public abstract class ExternalResourceExtension
implements BeforeTestExecutionCallback, AfterTestExecutionCallback {
@Override
public void beforeTestExecution(ExtensionContext context) throws Exception {
before(context);
}
@Override
public void afterTestExecution(ExtensionContext context) throws Exception {
after(context);
}
protected abstract void before(ExtensionContext context);
protected abstract void after(ExtensionContext context);
}