0
我有以下注释和junit测试的规则初始化部分。 目标是使用不同的配置并尽可能简化测试。
// Annotation
@Retention(RetentionPolicy.RUNTIME)
public @interface ConnectionParams {
public String username();
public String password() default "";
}
// Part of the test
@ConnectionParams(username = "john")
@Rule
public ConnectionTestRule ctr1 = new ConnectionTestRule();
@ConnectionParams(username = "doe", password = "secret")
@Rule
public ConnectionTestRule ctr2 = new ConnectionTestRule();
现在我想访问下面的TestRule中的注释参数,但它没有找到任何注释。
public class ConnectionTestRule implements TestRule {
public Statement apply(Statement arg0, Description arg1) {
if (this.getClass().isAnnotationPresent(ConnectionParams.class)) {
... // do stuff
}
}
}
如何访问TestRule内的注释?
我更新了这个问题,我的目标是,运行不同配置的测试 –
我已经更新了答案。您需要首先从您的对象/字段中找到注释,然后从中获取注释,并最终将配置传递给您的测试。 – ScanQR
TestRule不知道它将在何处使用,因此您所建议的“class_in_which_object_created.getDeclaredFields()”将不起作用出。 –