你可以这样做:
public class MyExtension implements BeforeEachCallback {
@Override
public void beforeEach(ExtensionContext context) {
context.getTestInstance().ifPresent(testInstance -> {
List<Field> driverFields = AnnotationSupport.findAnnotatedFields(testInstance.getClass(), MyDriver.class);
for (Field driverField : driverFields) {
try {
Object fieldValue = driverField.get(testInstance);
// Do whatever you want with the field or its value
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
});
}
}
然后在这样的测试类中的每个测试之前调用它:
@MyDriver
class SomeTestThatUsesDriver {
@MyDriver
Object fieldWithAnnotation = "whatever";
@Test
void aTest() {
...
}
}
但是,我不会使用注释@MyDriver
来添加扩展名和标记字段。我宁愿得到一个额外的注释,@MyDriverField
或者直接在测试类中添加扩展。