前言:
我有以下注释和 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 中的注释?
最佳答案
您的申请不正确。
在类级别应用自定义注释,而不是按照您完成的方式。
// Apply on class instead
@ConnectionParams(username = "john")
public class ConnectionTestRule {....
那么你的代码应该可以工作,
public class ConnectionTestRule implements TestRule {
public Statement apply(Statement arg0, Description arg1) {
//get annotation from current (this) class
if (this.getClass().isAnnotationPresent(ConnectionParams.class)) {
... // do stuff
}
}
}
编辑:更新问题后。
您需要首先使用反射获取字段,以便找到您创建的每个 ConnectionTestRule 对象,并从中获取注释以获取所需的配置。
for(Field field : class_in_which_object_created.getDeclaredFields()){
Class type = field.getType();
String name = field.getName();
//it will get annotations from each of your
//public ConnectionTestRule ctr1 = new ConnectionTestRule();
//public ConnectionTestRule ctr2 = new ConnectionTestRule();
Annotation[] annotations = field.getDeclaredAnnotations();
/*
*
*once you get your @ConnectionParams then pass it respective tests
*
*/
}
关于java - 访问 TestRule 中的自定义注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40674313/