如何将参数传递给@Provide?

How can I pass parameters to @Provide?

有没有办法将参数传递给@Provide?我想要等同于以下内容的内容:

@Property
void test(@ForAll("charSequence", 2, 5) CharSequence cs) {
    // test property on cs, which is an arbitrary CharSequence of length minimum 2 and maximum length 5
}

@Provide
Arbitrary<CharSequence> charSequence(int minLength, int maxLength) {
    Arbitrary<String> stringArbitrary = Arbitraries.strings().ofMinLength(minLength).ofMaxLength(maxLength).injectNull(0.01);
    Arbitrary<StringBuffer> stringBufferArbitrary = stringArbitrary.map
        (str -> null == str ? null : new StringBuffer(str));
    Arbitrary<StringBuilder> stringBuilderArbitrary = stringArbitrary.map
        (str -> null == str ? null : new StringBuilder(str));
    return Arbitraries.oneOf(stringArbitrary, stringBufferArbitrary, stringBuilderArbitrary);
}

我尝试创建自定义注释

public @interface Length {
    int min();
    int max();
}

并按照 Provider Methods with Parameters 中的建议将其用作 void test(@ForAll("charSequence") @Length(min = 2, max = 5) CharSequence cs),但 TypeUsage 似乎没有选择自定义注释 @Length。 (只选择了 @ForAll。)

jqwik 中目前没有直接将参数传递给提供程序方法的机制。但是,注释机制应该按照您的建议工作:

@Property
void test(@ForAll("charSequence") @Length(min = 2, max = 5)  CharSequence cs) {
    System.out.println(cs);
}

@Provide
Arbitrary<CharSequence> charSequence(TypeUsage typeUsage) {
    Optional<Length> optionalLength = typeUsage.findAnnotation(Length.class);
    int minLength = optionalLength.map(l -> l.min()).orElse(1);
    int maxLength = optionalLength.map(l -> l.max()).orElse(255);

    Arbitrary<String> stringArbitrary = Arbitraries.strings().ofMinLength(minLength).ofMaxLength(maxLength);
    Arbitrary<StringBuffer> stringBufferArbitrary =
        stringArbitrary.map(str -> null == str ? null : new StringBuffer(str));
    Arbitrary<StringBuilder> stringBuilderArbitrary =
        stringArbitrary.map(str -> null == str ? null : new StringBuilder(str));

    return Arbitraries.oneOf(
            stringArbitrary, 
            stringBufferArbitrary, 
            stringBuilderArbitrary
    );
}

我猜你忘记为 @Length 打开运行时保留,否则注释将被编译器删除:

@Target({ ElementType.ANNOTATION_TYPE, ElementType.PARAMETER, ElementType.TYPE_USE })
@Retention(RetentionPolicy.RUNTIME)
@interface Length {
    int min();
    int max();
}

以上代码应生成类似于(长度在 2 到 5 之间的序列)的输出:

ꭀ訂
쯈쓁緈ﵬ
堰⾞ᒽ뒡ՙ
ᒽ뒡
쳨任๔蔢
涼嵒퓗
⫈ࣦ᩿쯧佺
佺㺻
䲠燷怟藤
...