rima.j
rima.j

Reputation: 31

How to generate a sorted array of numbers with jqwik

I am using java jqwik for property based testing, I want to generate sorted array, my code so far:

@Provide
Integer[] arrProvider() {
    Arbitrary<Integer> integerArbitrary = Arbitraries.integers().between(0, 100);
    Arbitrary<Integer[]> arrayArbitrary = integerArbitrary.array(Integer[].class).ofMinSize(0).ofMaxSize(30);

 // how to make my arbitrary sorted ? and I want to return it as array of Integers?
}

Upvotes: 2

Views: 1531

Answers (1)

johanneslink
johanneslink

Reputation: 5351

There are two issues that might bite you here:

  1. What return type do provider methods have?
  2. How to transform a generated object?

Let's tackle it in two steps:

In jqwik generators are exposed as Arbitrary<TypeToGenerate> so the signature of your provider method is:

@Provide
Arbitrary<Integer[]> arrProvider() {
    return ...;
}

Arbitraries are actually factories of generators and they provide all the capabilities to filter, combine and map. Mapping is what we need for the second part of the question:

integerArbitrary
    .array(Integer[].class).ofMinSize(0).ofMaxSize(30)
    .map(anArray -> {
        Arrays.sort(anArray);
        return anArray;
    });

Let's combine that together and use it in a property:

@Property
void arrayIsSorted(@ForAll("arrProvider") Integer[] array) {
    System.out.println(Arrays.toString(array));
}

@Provide
Arbitrary<Integer[]> arrProvider() {
    Arbitrary<Integer> integerArbitrary = Arbitraries.integers().between(0, 100);
    return integerArbitrary
        .array(Integer[].class).ofMinSize(0).ofMaxSize(30)
        .map(anArray -> {
            Arrays.sort(anArray);
            return anArray;
        });
}

The output now should show sorted arrays similiar to that:

[0, 1, 27, 33, 47, 80, 84, 91, 92]
[1, 2, 2, 5, 5, 5, 15, 16, 38, 39, 44, 54, 54, 63, 71, 78, 86, 93, 93, 100]
[0, 3, 4, 4, 4, 11, 12, 20, 21, 25, 44, 51, 55, 62, 66, 75, 78, 80, 81, 87, 90, 92, 94]
[3, 45, 45, 78, 95, 96]

Only more of it.

Upvotes: 3

Related Questions