由于您要测试 ParameterResolver 实现而不是 JUnit 引擎,因此单元测试的入口点应该是provideArguments
您的实现方法。JUnit 捕获此方法引发的每个异常并将其添加为新的 ParameterResolutionException 的原因。有两种可能的方法:
A)
如果您的实现应该调用多个方法,ExtensionContext
则将这些方法与您的注释一起模拟。并调用provideArguments
你的实现。
B)
如果您的实现应该使用ExtensionContext
only 来获取注解并且不做任何值得测试的事情,那么将主要功能移动到自己的方法中(例如accept(MyAnnotation)
)并测试此方法。例如,请参阅此处的 JUnit 开发人员如何使用 CVSSource 注释。
ResourceFilesArgumentsProvider
这是我的/ResourceFilesSource
注释的示例测试用例:
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ResourceFilesArgumentsProviderTest {
@Test
public void nonExistingDirectory() throws Exception {
ResourceFilesSource annotation = resourceFiles("/non-existing-dir");
AnnotatedElement annotatedElement = mock(AnnotatedElement.class);
when(annotatedElement.getAnnotation(ResourceFilesSource.class))
.thenReturn(annotation);
ExtensionContext context = mock(ExtensionContext.class);
when(context.getElement()).thenReturn(Optional.of(annotatedElement));
when(context.getTestClass()).thenReturn(Optional.of(getClass()));
assertThrows(NoSuchFileException.class, () -> provideArguments(context));
}
private Stream<Object[]> provideArguments(ExtensionContext context) throws Exception {
ResourceFilesArgumentsProvider provider = new ResourceFilesArgumentsProvider();
return provider.provideArguments(context).map(Arguments::get);
}
private ResourceFilesSource resourceFiles(String directory) {
/* mock the annotation with Mockito, or alternatively create
* an anonymous class with new ResourceFileSource() { ... }
*/
ResourceFilesSource annotation = mock(ResourceFilesSource.class);
when(annotation.directory()).thenReturn(directory);
return annotation;
}
}