【问题标题】:How to pass Date parameter to annotation and then validate it in junit 5 extension?如何将 Date 参数传递给注释,然后在 junit 5 扩展中验证它?
【发布时间】:2019-02-15 09:53:06
【问题描述】:

所以我有扩展名可以根据某些条件跳过测试。其中一个条件应该是日期,例如修复的目标日期,在这一天之前,我们将跳过测试:

public class KnownIssueExtension implements ExecutionCondition {
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {

    Date now = new Date();

    final Optional<Method> testMethod = context.getTestMethod();
    if (testMethod.isPresent()
            && testMethod.get().isAnnotationPresent(KnownIssue.class) && now.before(testMethod.get().getAnnotation(KnownIssue.class).date())) {
        return disabled(testMethod.get().getAnnotation(KnownIssue.class).description());
    }
    return enabled("");
}

所以我想将当前日期放入像参数这样的注释中,但我不能分配任何默认值或类似的东西。

现在看起来像:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface KnownIssue {
    String description()
            default "Please set the reason for the expected failure like: @KnownIssue(description = \"TPSVC-12345\")";

Date date()
            default "I DONT KNOW WHAT SHOULD BE HERE, I have tried new Date(), but it's not working"

}

【问题讨论】:

  • 您需要多具体的日期?注释值需要是常量表达式,所以你会遇到Date 对象。您可以使用String 并要求人们填写 ISO8601 或类似的内容。或者有多个int(或其他enummonth等)成员year()month()等。甚至@Date的另一个注释可以做到这一点,所以你可以重用它在其他地方。

标签: java junit interface annotations junit5


【解决方案1】:

按如下方式实现您的注释。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface KnownIssue {

    String since();

    String description() default "";
}

since 属性必须符合 ISO 标准日期格式 YYYY-MM-DD 的文档。

然后将String 解析为java.util.Date(例如,通过java.text.DateFormat.parse(String))或java.time.LocalDate(例如,通过java.time.LocalDate.parse(CharSequence))。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多