/** * Chooses a char between min and max, bounds inclusive and chars distributed according to the * underlying random number generator. * * <p>Note: min and max are internally swapped if min > max. * * @param min lower bound * @param max upper bound * @return A new char generator */ static Gen<Character> choose(char min, char max) { if (min == max) { return ignored -> min; } else { return random -> (char) (int) Gen.choose((int) min, (int) max).apply(random); } }
@Test public void shouldFlatMapArbitrary() { final Arbitrary<Integer> arbitraryInt = size -> Gen.choose(-size, size); final Arbitrary<BinaryTree<Integer>> arbitraryTree = arbitraryInt.flatMap(i -> new ArbitraryBinaryTree(-i, i)); assertThat(arbitraryTree.apply(0).apply(new Random())).isNotNull(); }
@Override public Gen<BinaryTree<Integer>> apply(int n) { return random -> Gen.choose(minValue, maxValue) .flatMap( value -> { if (n == 0) { return Gen.of(BinaryTree.leaf(value)); } else { return Gen.frequency( Tuple.of(1, Gen.of(BinaryTree.leaf(value))), Tuple.of( 4, Gen.of( BinaryTree.branch( apply(n / 2).apply(random), value, apply(n / 2).apply(random))))); } }) .apply(random); }
@Test public void shouldMapArbitrary() { final Arbitrary<Integer> arbitraryInt = size -> Gen.choose(-size, size); final Arbitrary<BinaryTree<Integer>> arbitraryTree = arbitraryInt.map(BinaryTree::leaf); assertThat(arbitraryTree.apply(0).apply(new Random())).isNotNull(); }
@Test public void shouldCreateArbitraryString() { final Arbitrary<String> arbitrary = Arbitrary.string(Gen.choose('a', 'z')); final String actual = arbitrary.apply(10).apply(new Random()); assertThat(actual).isNotNull(); }