|
| 1 | +package com.baeldung.javaslang; |
| 2 | + |
| 3 | + |
| 4 | +import javaslang.CheckedFunction1; |
| 5 | +import javaslang.collection.Stream; |
| 6 | +import javaslang.test.Arbitrary; |
| 7 | +import javaslang.test.CheckResult; |
| 8 | +import javaslang.test.Property; |
| 9 | +import org.junit.Test; |
| 10 | + |
| 11 | +public class PropertyBasedTest { |
| 12 | + |
| 13 | + public Stream<String> stringsSupplier() { |
| 14 | + return Stream.from(0).map(i -> { |
| 15 | + boolean divByTwo = i % 2 == 0; |
| 16 | + boolean divByFive = i % 5 == 0; |
| 17 | + |
| 18 | + if(divByFive && divByTwo){ |
| 19 | + return "DividedByTwoAndFiveWithoutRemainder"; |
| 20 | + }else if(divByFive){ |
| 21 | + return "DividedByFiveWithoutRemainder"; |
| 22 | + }else if(divByTwo){ |
| 23 | + return "DividedByTwoWithoutRemainder"; |
| 24 | + } |
| 25 | + return ""; |
| 26 | + }); |
| 27 | + } |
| 28 | + |
| 29 | + @Test |
| 30 | + public void givenArbitrarySeq_whenCheckThatEverySecondElementIsEqualToString_thenTestPass() { |
| 31 | + //given |
| 32 | + Arbitrary<Integer> multiplesOf2 = Arbitrary.integer() |
| 33 | + .filter(i -> i > 0) |
| 34 | + .filter(i -> i % 2 == 0 && i % 5 != 0); |
| 35 | + |
| 36 | + //when |
| 37 | + CheckedFunction1<Integer, Boolean> mustEquals = |
| 38 | + i -> stringsSupplier().get(i).equals("DividedByTwoWithoutRemainder"); |
| 39 | + |
| 40 | + |
| 41 | + //then |
| 42 | + CheckResult result = Property |
| 43 | + .def("Every second element must equal to DividedByTwoWithoutRemainder") |
| 44 | + .forAll(multiplesOf2) |
| 45 | + .suchThat(mustEquals) |
| 46 | + .check(10_000, 100); |
| 47 | + |
| 48 | + result.assertIsSatisfied(); |
| 49 | + } |
| 50 | + |
| 51 | + @Test |
| 52 | + public void givenArbitrarySeq_whenCheckThatEveryFifthElementIsEqualToString_thenTestPass() { |
| 53 | + //given |
| 54 | + Arbitrary<Integer> multiplesOf5 = Arbitrary.integer() |
| 55 | + .filter(i -> i > 0) |
| 56 | + .filter(i -> i % 5 == 0 && i % 2 == 0); |
| 57 | + |
| 58 | + //when |
| 59 | + CheckedFunction1<Integer, Boolean> mustEquals = i -> |
| 60 | + stringsSupplier().get(i).endsWith("DividedByTwoAndFiveWithoutRemainder"); |
| 61 | + |
| 62 | + //then |
| 63 | + Property.def("Every fifth element must equal to DividedByTwoAndFiveWithoutRemainder") |
| 64 | + .forAll(multiplesOf5) |
| 65 | + .suchThat(mustEquals) |
| 66 | + .check(10_000, 1_000) |
| 67 | + .assertIsSatisfied(); |
| 68 | + } |
| 69 | +} |
0 commit comments