How to use internalFilteredOn method of org.assertj.core.api.AbstractObjectArrayAssert class

Best Assertj code snippet using org.assertj.core.api.AbstractObjectArrayAssert.internalFilteredOn

Source:AbstractIterableAssert.java Github

copy

Full Screen

...2418 */2419 @CheckReturnValue2420 public <T> SELF filteredOn(Function<? super ELEMENT, T> function, T expectedValue) {2421 checkArgument(function != null, "The filter function should not be null");2422 // call internalFilteredOn to avoid double proxying in soft assertions2423 return internalFilteredOn(element -> java.util.Objects.equals(function.apply(element), expectedValue));2424 }2425 /**2426 * Filters the iterable under test keeping only elements matching the given assertions specified with a {@link Consumer}.2427 * <p>2428 * Example : check young hobbits whose age &lt; 34:2429 *2430 * <pre><code class='java'> TolkienCharacter pippin = new TolkienCharacter("Pippin", 28, HOBBIT);2431 * TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);2432 * TolkienCharacter merry = new TolkienCharacter("Merry", 36, HOBBIT);2433 * TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);2434 *2435 * List&lt;TolkienCharacter&gt; hobbits = list(frodo, sam, merry, pippin);2436 *2437 * assertThat(hobbits).filteredOnAssertions(hobbit -&gt; assertThat(hobbit.age).isLessThan(34))2438 * .containsOnly(frodo, pippin);</code></pre>2439 *2440 * @param elementAssertions containing AssertJ assertions to filter on2441 * @return a new assertion object with the filtered iterable under test2442 * @throws IllegalArgumentException if the given predicate is {@code null}.2443 * @since 3.11.02444 */2445 public SELF filteredOnAssertions(Consumer<? super ELEMENT> elementAssertions) {2446 checkArgument(elementAssertions != null, "The element assertions should not be null");2447 List<? extends ELEMENT> filteredIterable = stream(actual.spliterator(), false).filter(byPassingAssertions(elementAssertions))2448 .collect(toList());2449 return newAbstractIterableAssert(filteredIterable).withAssertionState(myself);2450 }2451 // navigable assertions2452 /**2453 * Navigate and allow to perform assertions on the first element of the {@link Iterable} under test.2454 * <p>2455 * By default available assertions after {@code first()} are {@code Object} assertions, it is possible though to2456 * get more specific assertions if you create {@code IterableAssert} with either:2457 * <ul>2458 * <li>the element assert class, see: {@link Assertions#assertThat(Iterable, Class) assertThat(Iterable, element assert class)}</li>2459 * <li>an assert factory used that knows how to create elements assertion, see: {@link Assertions#assertThat(Iterable, AssertFactory) assertThat(Iterable, element assert factory)}</li>2460 * </ul>2461 * <p>2462 * Example: default {@code Object} assertions2463 * <pre><code class='java'> // default iterable assert =&gt; element assert is ObjectAssert2464 * Iterable&lt;TolkienCharacter&gt; hobbits = newArrayList(frodo, sam, pippin);2465 *2466 * // assertion succeeds, only Object assertions are available after first()2467 * assertThat(hobbits).first()2468 * .isEqualTo(frodo);2469 *2470 * // assertion fails2471 * assertThat(hobbits).first()2472 * .isEqualTo(pippin);</code></pre>2473 * <p>2474 * If you have created the Iterable assertion using an {@link AssertFactory} or the element assert class,2475 * you will be able to chain {@code first()} with more specific typed assertion.2476 * <p>2477 * Example: use of {@code String} assertions after {@code first()}2478 * <pre><code class='java'> Iterable&lt;String&gt; hobbits = newArrayList("Frodo", "Sam", "Pippin");2479 *2480 * // assertion succeeds2481 * // String assertions are available after first()2482 * assertThat(hobbits, StringAssert.class).first()2483 * .startsWith("Fro")2484 * .endsWith("do");2485 * // assertion fails2486 * assertThat(hobbits, StringAssert.class).first()2487 * .startsWith("Pip");</code></pre>2488 *2489 * @return the assertion on the first element2490 * @throws AssertionError if the actual {@link Iterable} is empty.2491 * @since 2.5.0 / 3.5.02492 * @see #first(InstanceOfAssertFactory)2493 */2494 @CheckReturnValue2495 public ELEMENT_ASSERT first() {2496 return internalFirst();2497 }2498 /**2499 * Navigate and allow to perform assertions on the first element of the {@link Iterable} under test.2500 * <p>2501 * The {@code assertFactory} parameter allows to specify an {@link InstanceOfAssertFactory}, which is used to get the2502 * assertions narrowed to the factory type.2503 * <p>2504 * Example: use of {@code String} assertions after {@code first(as(InstanceOfAssertFactories.STRING)}2505 * <pre><code class='java'> Iterable&lt;String&gt; hobbits = newArrayList("Frodo", "Sam", "Pippin");2506 *2507 * // assertion succeeds2508 * assertThat(hobbits).first(as(InstanceOfAssertFactories.STRING))2509 * .startsWith("Fro")2510 * .endsWith("do");2511 * // assertion fails2512 * assertThat(hobbits).first(as(InstanceOfAssertFactories.STRING))2513 * .startsWith("Pip");2514 * // assertion fails because of wrong factory type2515 * assertThat(hobbits).first(as(InstanceOfAssertFactories.INTEGER))2516 * .isZero();</code></pre>2517 *2518 * @param <ASSERT> the type of the resulting {@code Assert}2519 * @param assertFactory the factory which verifies the type and creates the new {@code Assert}2520 * @return a new narrowed {@link Assert} instance for assertions chaining on the first element2521 * @throws AssertionError if the actual {@link Iterable} is empty.2522 * @throws NullPointerException if the given factory is {@code null}2523 * @since 3.14.02524 */2525 @CheckReturnValue2526 public <ASSERT extends AbstractAssert<?, ?>> ASSERT first(InstanceOfAssertFactory<?, ASSERT> assertFactory) {2527 return internalFirst().asInstanceOf(assertFactory);2528 }2529 private ELEMENT_ASSERT internalFirst() {2530 isNotEmpty();2531 return toAssert(actual.iterator().next(), navigationDescription("check first element"));2532 }2533 /**2534 * Navigate and allow to perform assertions on the last element of the {@link Iterable} under test.2535 * <p>2536 * By default available assertions after {@code last()} are {@code Object} assertions, it is possible though to2537 * get more specific assertions if you create {@code IterableAssert} with either:2538 * <ul>2539 * <li>the element assert class, see: {@link Assertions#assertThat(Iterable, Class) assertThat(Iterable, element assert class)}</li>2540 * <li>an assert factory used that knows how to create elements assertion, see: {@link Assertions#assertThat(Iterable, AssertFactory) assertThat(Iterable, element assert factory)}</li>2541 * </ul>2542 * <p>2543 * Example: default {@code Object} assertions2544 * <pre><code class='java'> // default iterable assert =&gt; element assert is ObjectAssert2545 * Iterable&lt;TolkienCharacter&gt; hobbits = newArrayList(frodo, sam, pippin);2546 *2547 * // assertion succeeds, only Object assertions are available after last()2548 * assertThat(hobbits).last()2549 * .isEqualTo(pippin);2550 *2551 * // assertion fails2552 * assertThat(hobbits).last()2553 * .isEqualTo(frodo);</code></pre>2554 * <p>2555 * If you have created the Iterable assertion using an {@link AssertFactory} or the element assert class,2556 * you will be able to chain {@code last()} with more specific typed assertion.2557 * <p>2558 * Example: use of {@code String} assertions after {@code last()}2559 * <pre><code class='java'> Iterable&lt;String&gt; hobbits = newArrayList("Frodo", "Sam", "Pippin");2560 *2561 * // assertion succeeds2562 * // String assertions are available after last()2563 * assertThat(hobbits, StringAssert.class).last()2564 * .startsWith("Pi")2565 * .endsWith("in");2566 * // assertion fails2567 * assertThat(hobbits, StringAssert.class).last()2568 * .startsWith("Fro");</code></pre>2569 *2570 * @return the assertion on the last element2571 * @throws AssertionError if the actual {@link Iterable} is empty.2572 * @since 2.5.0 / 3.5.02573 * @see #last(InstanceOfAssertFactory)2574 */2575 @CheckReturnValue2576 public ELEMENT_ASSERT last() {2577 return internalLast();2578 }2579 /**2580 * Navigate and allow to perform assertions on the last element of the {@link Iterable} under test.2581 * <p>2582 * The {@code assertFactory} parameter allows to specify an {@link InstanceOfAssertFactory}, which is used to get the2583 * assertions narrowed to the factory type.2584 * <p>2585 * Example: use of {@code String} assertions after {@code last(as(InstanceOfAssertFactories.STRING)}2586 * <pre><code class='java'> Iterable&lt;String&gt; hobbits = newArrayList("Frodo", "Sam", "Pippin");2587 *2588 * // assertion succeeds2589 * assertThat(hobbits).last(as(InstanceOfAssertFactories.STRING))2590 * .startsWith("Pip")2591 * .endsWith("pin");2592 * // assertion fails2593 * assertThat(hobbits).last(as(InstanceOfAssertFactories.STRING))2594 * .startsWith("Fro");2595 * // assertion fails because of wrong factory type2596 * assertThat(hobbits).last(as(InstanceOfAssertFactories.INTEGER))2597 * .isZero();</code></pre>2598 *2599 * @param <ASSERT> the type of the resulting {@code Assert}2600 * @param assertFactory the factory which verifies the type and creates the new {@code Assert}2601 * @return a new narrowed {@link Assert} instance for assertions chaining on the last element2602 * @throws AssertionError if the actual {@link Iterable} is empty.2603 * @throws NullPointerException if the given factory is {@code null}2604 * @since 3.14.02605 */2606 @CheckReturnValue2607 public <ASSERT extends AbstractAssert<?, ?>> ASSERT last(InstanceOfAssertFactory<?, ASSERT> assertFactory) {2608 return internalLast().asInstanceOf(assertFactory);2609 }2610 private ELEMENT_ASSERT internalLast() {2611 isNotEmpty();2612 return toAssert(lastElement(), navigationDescription("check last element"));2613 }2614 private ELEMENT lastElement() {2615 if (actual instanceof List) {2616 @SuppressWarnings("unchecked")2617 List<? extends ELEMENT> list = (List<? extends ELEMENT>) actual;2618 return list.get(list.size() - 1);2619 }2620 Iterator<? extends ELEMENT> actualIterator = actual.iterator();2621 ELEMENT last = actualIterator.next();2622 while (actualIterator.hasNext()) {2623 last = actualIterator.next();2624 }2625 return last;2626 }2627 /**2628 * Navigate and allow to perform assertions on the chosen element of the {@link Iterable} under test.2629 * <p>2630 * By default available assertions after {@code element(index)} are {@code Object} assertions, it is possible though to2631 * get more specific assertions if you create {@code IterableAssert} with either:2632 * <ul>2633 * <li>the element assert class, see: {@link Assertions#assertThat(Iterable, Class) assertThat(Iterable, element assert class)}</li>2634 * <li>an assert factory used that knows how to create elements assertion, see: {@link Assertions#assertThat(Iterable, AssertFactory) assertThat(Iterable, element assert factory)}</li>2635 * </ul>2636 * <p>2637 * Example: default {@code Object} assertions2638 * <pre><code class='java'> // default iterable assert =&gt; element assert is ObjectAssert2639 * Iterable&lt;TolkienCharacter&gt; hobbits = newArrayList(frodo, sam, pippin);2640 *2641 * // assertion succeeds, only Object assertions are available after element(index)2642 * assertThat(hobbits).element(1)2643 * .isEqualTo(sam);2644 *2645 * // assertion fails2646 * assertThat(hobbits).element(1)2647 * .isEqualTo(pippin);</code></pre>2648 * <p>2649 * If you have created the Iterable assertion using an {@link AssertFactory} or the element assert class,2650 * you will be able to chain {@code element(index)} with more specific typed assertion.2651 * <p>2652 * Example: use of {@code String} assertions after {@code element(index)}2653 * <pre><code class='java'> Iterable&lt;String&gt; hobbits = newArrayList("Frodo", "Sam", "Pippin");2654 *2655 * // assertion succeeds2656 * // String assertions are available after element(index)2657 * assertThat(hobbits, StringAssert.class).element(1)2658 * .startsWith("Sa")2659 * .endsWith("am");2660 * // assertion fails2661 * assertThat(hobbits, StringAssert.class).element(1)2662 * .startsWith("Fro");</code></pre>2663 *2664 * @param index the element's index2665 * @return the assertion on the given element2666 * @throws AssertionError if the given index is out of bound.2667 * @since 2.5.0 / 3.5.02668 * @see #element(int, InstanceOfAssertFactory)2669 */2670 @CheckReturnValue2671 public ELEMENT_ASSERT element(int index) {2672 return internalElement(index);2673 }2674 /**2675 * Navigate and allow to perform assertions on the chosen element of the {@link Iterable} under test.2676 * <p>2677 * The {@code assertFactory} parameter allows to specify an {@link InstanceOfAssertFactory}, which is used to get the2678 * assertions narrowed to the factory type.2679 * <p>2680 * Example: use of {@code String} assertions after {@code element(index, as(InstanceOfAssertFactories.STRING)}2681 * <pre><code class='java'> Iterable&lt;String&gt; hobbits = newArrayList("Frodo", "Sam", "Pippin");2682 *2683 * // assertion succeeds2684 * assertThat(hobbits).element(1, as(InstanceOfAssertFactories.STRING))2685 * .startsWith("Sa")2686 * .endsWith("am");2687 * // assertion fails2688 * assertThat(hobbits).element(1, as(InstanceOfAssertFactories.STRING))2689 * .startsWith("Fro");2690 * // assertion fails because of wrong factory type2691 * assertThat(hobbits).element(1, as(InstanceOfAssertFactories.INTEGER))2692 * .isZero();</code></pre>2693 *2694 * @param <ASSERT> the type of the resulting {@code Assert}2695 * @param index the element's index2696 * @param assertFactory the factory which verifies the type and creates the new {@code Assert}2697 * @return a new narrowed {@link Assert} instance for assertions chaining on the element at the given index2698 * @throws AssertionError if the given index is out of bound.2699 * @throws NullPointerException if the given factory is {@code null}2700 * @since 3.14.02701 */2702 @CheckReturnValue2703 public <ASSERT extends AbstractAssert<?, ?>> ASSERT element(int index, InstanceOfAssertFactory<?, ASSERT> assertFactory) {2704 return internalElement(index).asInstanceOf(assertFactory);2705 }2706 private ELEMENT_ASSERT internalElement(int index) {2707 isNotEmpty();2708 assertThat(index).describedAs(navigationDescription("check index validity"))2709 .isBetween(0, IterableUtil.sizeOf(actual) - 1);2710 ELEMENT elementAtIndex;2711 if (actual instanceof List) {2712 @SuppressWarnings("unchecked")2713 List<? extends ELEMENT> list = (List<? extends ELEMENT>) actual;2714 elementAtIndex = list.get(index);2715 } else {2716 Iterator<? extends ELEMENT> actualIterator = actual.iterator();2717 for (int i = 0; i < index; i++) {2718 actualIterator.next();2719 }2720 elementAtIndex = actualIterator.next();2721 }2722 return toAssert(elementAtIndex, navigationDescription("element at index " + index));2723 }2724 /**2725 * Verifies that the {@link Iterable} under test contains a single element and allows to perform assertions that element.2726 * <p>2727 * This is a shorthand for <code>hasSize(1).first()</code>.2728 * <p>2729 * By default available assertions after {@code singleElement()} are {@code Object} assertions, it is possible though to2730 * get more specific assertions if you create {@code IterableAssert} with either:2731 * <ul>2732 * <li>the element assert class, see: {@link Assertions#assertThat(Iterable, Class) assertThat(Iterable, element assert class)}</li>2733 * <li>an assert factory used that knows how to create elements assertion, see: {@link Assertions#assertThat(Iterable, AssertFactory) assertThat(Iterable, element assert factory)}</li>2734 * <li>the general <code>assertThat(Iterable)</code> and narrow down the single element with an assert factory, see: {@link #singleElement(InstanceOfAssertFactory) singleElement(element assert factory)}</li>2735 * </ul>2736 * <p>2737 * Example: default {@code Object} assertions2738 * <pre><code class='java'> List&lt;String&gt; babySimpsons = list("Maggie");2739 *2740 * // assertion succeeds, only Object assertions are available after singleElement()2741 * assertThat(babySimpsons).singleElement()2742 * .isEqualTo("Maggie");2743 *2744 * // assertion fails2745 * assertThat(babySimpsons).singleElement()2746 * .isEqualTo("Homer");2747 *2748 * // assertion fails because list contains no elements2749 * assertThat(emptyList()).singleElement();2750 *2751 *2752 * // assertion fails because list contains more than one element2753 * List&lt;String&gt; simpsons = list("Homer", "Marge", "Lisa", "Bart", "Maggie");2754 * assertThat(simpsons).singleElement();</code></pre>2755 * <p>2756 * If you have created the Iterable assertion using an {@link AssertFactory} or the element assert class,2757 * you will be able to chain {@code singleElement()} with more specific typed assertion.2758 * <p>2759 * Example: use of {@code String} assertions after {@code singleElement()}2760 * <pre><code class='java'> List&lt;String&gt; babySimpsons = list("Maggie");2761 *2762 * // assertion succeeds2763 * // String assertions are available after singleElement()2764 * assertThat(babySimpsons, StringAssert.class).singleElement()2765 * .startsWith("Mag");2766 *2767 * // InstanceOfAssertFactories.STRING is an AssertFactory for String assertions2768 * assertThat(babySimpsons, InstanceOfAssertFactories.STRING).singleElement()2769 * .startsWith("Mag");2770 * // better readability with import static InstanceOfAssertFactories.STRING and Assertions.as2771 * assertThat(babySimpsons, as(STRING)).singleElement()2772 * .startsWith("Mag");2773 *2774 * // assertions fail2775 * assertThat(babySimpsons, StringAssert.class).singleElement()2776 * .startsWith("Lis");2777 * // failure as the single element is not an int/Integer2778 * assertThat(babySimpsons, IntegerAssert.class).singleElement()2779 * .startsWith("Lis");</code></pre>2780 *2781 * @return the assertion on the first element2782 * @throws AssertionError if the actual {@link Iterable} does not contain exactly one element.2783 * @since 3.17.02784 * @see #singleElement(InstanceOfAssertFactory)2785 */2786 @CheckReturnValue2787 public ELEMENT_ASSERT singleElement() {2788 return internalSingleElement();2789 }2790 /**2791 * Verifies that the {@link Iterable} under test contains a single element and allows to perform assertions on that element.<br>2792 * The assertions are strongly typed according to the given {@link AssertFactory} parameter.2793 * <p>2794 * This is a shorthand for <code>hasSize(1).first(assertFactory)</code>.2795 * <p>2796 * Example: use of {@code String} assertions after {@code singleElement(as(STRING)}2797 * <pre><code class='java'> import static org.assertj.core.api.InstanceOfAssertFactories.STRING;2798 * import static org.assertj.core.api.InstanceOfAssertFactories.INTEGER;2799 * import static org.assertj.core.api.Assertions.as; // syntactic sugar2800 *2801 * List&lt;String&gt; babySimpsons = list("Maggie");2802 *2803 * // assertion succeeds2804 * assertThat(babySimpsons).singleElement(as(STRING))2805 * .startsWith("Mag");2806 *2807 * // assertion fails2808 * assertThat(babySimpsons).singleElement(as(STRING))2809 * .startsWith("Lis");2810 *2811 * // assertion fails because of wrong factory type2812 * assertThat(babySimpsons).singleElement(as(INTEGER))2813 * .isZero();2814 *2815 * // assertion fails because list contains no elements2816 * assertThat(emptyList()).singleElement(as(STRING));2817 *2818 * // assertion fails because list contains more than one element2819 * List&lt;String&gt; simpsons = list("Homer", "Marge", "Lisa", "Bart", "Maggie");2820 * assertThat(simpsons).singleElement(as(STRING));</code></pre>2821 *2822 * @param <ASSERT> the type of the resulting {@code Assert}2823 * @param assertFactory the factory which verifies the type and creates the new {@code Assert}2824 * @return a new narrowed {@link Assert} instance for assertions chaining on the single element2825 * @throws AssertionError if the actual {@link Iterable} does not contain exactly one element.2826 * @throws NullPointerException if the given factory is {@code null}.2827 * @since 3.17.02828 */2829 @CheckReturnValue2830 public <ASSERT extends AbstractAssert<?, ?>> ASSERT singleElement(InstanceOfAssertFactory<?, ASSERT> assertFactory) {2831 return internalSingleElement().asInstanceOf(assertFactory);2832 }2833 private ELEMENT_ASSERT internalSingleElement() {2834 iterables.assertHasSize(info, actual, 1);2835 return internalFirst();2836 }2837 protected abstract ELEMENT_ASSERT toAssert(ELEMENT value, String description);2838 protected String navigationDescription(String propertyName) {2839 String text = descriptionText();2840 if (Strings.isNullOrEmpty(text)) {2841 text = removeAssert(this.getClass().getSimpleName());2842 }2843 return text + " " + propertyName;2844 }2845 private static String removeAssert(String text) {2846 return text.endsWith(ASSERT) ? text.substring(0, text.length() - ASSERT.length()) : text;2847 }2848 /**2849 * Filters the iterable under test keeping only elements matching the given {@link Predicate}.2850 * <p>2851 * Example : check old employees whose age &gt; 100:2852 *2853 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);2854 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);2855 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);2856 *2857 * List&lt;Employee&gt; employees = newArrayList(yoda, luke, obiwan);2858 *2859 * assertThat(employees).filteredOn(employee -&gt; employee.getAge() &gt; 100)2860 * .containsOnly(yoda, obiwan);</code></pre>2861 *2862 * @param predicate the filter predicate2863 * @return a new assertion object with the filtered iterable under test2864 * @throws IllegalArgumentException if the given predicate is {@code null}.2865 */2866 public SELF filteredOn(Predicate<? super ELEMENT> predicate) {2867 return internalFilteredOn(predicate);2868 }2869 /**2870 * {@inheritDoc}2871 */2872 @Override2873 public SELF allMatch(Predicate<? super ELEMENT> predicate) {2874 iterables.assertAllMatch(info, actual, predicate, PredicateDescription.GIVEN);2875 return myself;2876 }2877 /**2878 * {@inheritDoc}2879 */2880 @Override2881 public SELF allMatch(Predicate<? super ELEMENT> predicate, String predicateDescription) {2882 iterables.assertAllMatch(info, actual, predicate, new PredicateDescription(predicateDescription));2883 return myself;2884 }2885 /**2886 * {@inheritDoc}2887 */2888 @Override2889 public SELF allSatisfy(Consumer<? super ELEMENT> requirements) {2890 iterables.assertAllSatisfy(info, actual, requirements);2891 return myself;2892 }2893 @Override2894 public SELF anyMatch(Predicate<? super ELEMENT> predicate) {2895 iterables.assertAnyMatch(info, actual, predicate, PredicateDescription.GIVEN);2896 return myself;2897 }2898 /**2899 * Verifies that the zipped pairs of actual and other elements, i.e: (actual 1st element, other 1st element), (actual 2nd element, other 2nd element), ...2900 * all satisfy the given {@code zipRequirements}.2901 * <p>2902 * This assertion assumes that actual and other have the same size but they can contain different type of elements2903 * making it handy to compare objects converted to another type, for example Domain and View/DTO objects.2904 * <p>2905 * Example:2906 * <pre><code class='java'> List&lt;Adress&gt; addressModels = findGoodRestaurants();2907 * List&lt;AdressView&gt; addressViews = convertToView(addressModels);2908 *2909 * // compare addressViews and addressModels respective paired elements.2910 * assertThat(addressViews).zipSatisfy(addressModels, (AdressView view, Adress model) -&gt; {2911 * assertThat(view.getZipcode() + ' ' + view.getCity()).isEqualTo(model.getCityLine());2912 * assertThat(view.getStreet()).isEqualTo(model.getStreet().toUpperCase());2913 * });</code></pre>2914 *2915 * @param <OTHER_ELEMENT> the type of the other iterable elements.2916 * @param other the iterable to zip actual with.2917 * @param zipRequirements the given requirements that each pair must satisfy.2918 * @return {@code this} assertion object.2919 * @throws NullPointerException if the given zipRequirements {@link BiConsumer} is {@code null}.2920 * @throws NullPointerException if the other iterable to zip actual with is {@code null}.2921 * @throws AssertionError if the {@code Iterable} under test is {@code null}.2922 * @throws AssertionError if actual and other don't have the same size.2923 * @throws AssertionError if one or more pairs don't satisfy the given requirements.2924 * @since 3.9.02925 */2926 public <OTHER_ELEMENT> SELF zipSatisfy(Iterable<OTHER_ELEMENT> other,2927 BiConsumer<? super ELEMENT, OTHER_ELEMENT> zipRequirements) {2928 iterables.assertZipSatisfy(info, actual, other, zipRequirements);2929 return myself;2930 }2931 /**2932 * {@inheritDoc}2933 */2934 @Override2935 public SELF anySatisfy(Consumer<? super ELEMENT> requirements) {2936 iterables.assertAnySatisfy(info, actual, requirements);2937 return myself;2938 }2939 /**2940 * {@inheritDoc}2941 */2942 @Override2943 public SELF noneSatisfy(Consumer<? super ELEMENT> restrictions) {2944 iterables.assertNoneSatisfy(info, actual, restrictions);2945 return myself;2946 }2947 // override methods to avoid compilation error when chaining an AbstractAssert method with a AbstractIterableAssert2948 // one on raw types.2949 @Override2950 @CheckReturnValue2951 public SELF as(String description, Object... args) {2952 return super.as(description, args);2953 }2954 @Override2955 @CheckReturnValue2956 public SELF as(Description description) {2957 return super.as(description);2958 }2959 @Override2960 @CheckReturnValue2961 public SELF describedAs(Description description) {2962 return super.describedAs(description);2963 }2964 @Override2965 @CheckReturnValue2966 public SELF describedAs(String description, Object... args) {2967 return super.describedAs(description, args);2968 }2969 @Override2970 public SELF doesNotHave(Condition<? super ACTUAL> condition) {2971 return super.doesNotHave(condition);2972 }2973 @Override2974 public SELF doesNotHaveSameClassAs(Object other) {2975 return super.doesNotHaveSameClassAs(other);2976 }2977 @Override2978 public SELF has(Condition<? super ACTUAL> condition) {2979 return super.has(condition);2980 }2981 @Override2982 public SELF hasSameClassAs(Object other) {2983 return super.hasSameClassAs(other);2984 }2985 @Override2986 public SELF hasToString(String expectedToString) {2987 return super.hasToString(expectedToString);2988 }2989 @Override2990 public SELF is(Condition<? super ACTUAL> condition) {2991 return super.is(condition);2992 }2993 @Override2994 public SELF isEqualTo(Object expected) {2995 return super.isEqualTo(expected);2996 }2997 @Override2998 public SELF isExactlyInstanceOf(Class<?> type) {2999 return super.isExactlyInstanceOf(type);3000 }3001 @Override3002 public SELF isIn(Iterable<?> values) {3003 return super.isIn(values);3004 }3005 @Override3006 public SELF isIn(Object... values) {3007 return super.isIn(values);3008 }3009 @Override3010 public SELF isInstanceOf(Class<?> type) {3011 return super.isInstanceOf(type);3012 }3013 @Override3014 public SELF isInstanceOfAny(Class<?>... types) {3015 return super.isInstanceOfAny(types);3016 }3017 @Override3018 public SELF isNot(Condition<? super ACTUAL> condition) {3019 return super.isNot(condition);3020 }3021 @Override3022 public SELF isNotEqualTo(Object other) {3023 return super.isNotEqualTo(other);3024 }3025 @Override3026 public SELF isNotExactlyInstanceOf(Class<?> type) {3027 return super.isNotExactlyInstanceOf(type);3028 }3029 @Override3030 public SELF isNotIn(Iterable<?> values) {3031 return super.isNotIn(values);3032 }3033 @Override3034 public SELF isNotIn(Object... values) {3035 return super.isNotIn(values);3036 }3037 @Override3038 public SELF isNotInstanceOf(Class<?> type) {3039 return super.isNotInstanceOf(type);3040 }3041 @Override3042 public SELF isNotInstanceOfAny(Class<?>... types) {3043 return super.isNotInstanceOfAny(types);3044 }3045 @Override3046 public SELF isNotOfAnyClassIn(Class<?>... types) {3047 return super.isNotOfAnyClassIn(types);3048 }3049 @Override3050 public SELF isNotNull() {3051 return super.isNotNull();3052 }3053 @Override3054 public SELF isNotSameAs(Object other) {3055 return super.isNotSameAs(other);3056 }3057 @Override3058 public SELF isOfAnyClassIn(Class<?>... types) {3059 return super.isOfAnyClassIn(types);3060 }3061 @Override3062 public SELF isSameAs(Object expected) {3063 return super.isSameAs(expected);3064 }3065 @Override3066 public SELF noneMatch(Predicate<? super ELEMENT> predicate) {3067 iterables.assertNoneMatch(info, actual, predicate, PredicateDescription.GIVEN);3068 return myself;3069 }3070 @Override3071 @CheckReturnValue3072 public SELF overridingErrorMessage(String newErrorMessage, Object... args) {3073 return super.overridingErrorMessage(newErrorMessage, args);3074 }3075 @Override3076 @CheckReturnValue3077 public SELF usingDefaultComparator() {3078 return super.usingDefaultComparator();3079 }3080 @Override3081 @CheckReturnValue3082 public SELF usingComparator(Comparator<? super ACTUAL> customComparator) {3083 return usingComparator(customComparator, null);3084 }3085 @Override3086 @CheckReturnValue3087 public SELF usingComparator(Comparator<? super ACTUAL> customComparator, String customComparatorDescription) {3088 return super.usingComparator(customComparator, customComparatorDescription);3089 }3090 @Override3091 @CheckReturnValue3092 public SELF withFailMessage(String newErrorMessage, Object... args) {3093 return super.withFailMessage(newErrorMessage, args);3094 }3095 @Override3096 @CheckReturnValue3097 public SELF withThreadDumpOnError() {3098 return super.withThreadDumpOnError();3099 }3100 /**3101 * Returns an {@code Assert} object that allows performing assertions on the size of the {@link Iterable} under test.3102 * <p>3103 * Once this method is called, the object under test is no longer the {@link Iterable} but its size,3104 * to perform assertions on the {@link Iterable}, call {@link AbstractIterableSizeAssert#returnToIterable()}.3105 * <p>3106 * Example:3107 * <pre><code class='java'> Iterable&lt;Ring&gt; elvesRings = newArrayList(vilya, nenya, narya);3108 *3109 * // assertion will pass:3110 * assertThat(elvesRings).size().isGreaterThan(1)3111 * .isLessThanOrEqualTo(3)3112 * .returnToIterable().contains(narya)3113 * .doesNotContain(oneRing);3114 *3115 * // assertion will fail:3116 * assertThat(elvesRings).size().isGreaterThan(3);</code></pre>3117 *3118 * @return AbstractIterableSizeAssert built with the {@code Iterable}'s size.3119 * @throws NullPointerException if the given {@code Iterable} is {@code null}.3120 */3121 @SuppressWarnings({ "rawtypes", "unchecked" })3122 @CheckReturnValue3123 public AbstractIterableSizeAssert<SELF, ACTUAL, ELEMENT, ELEMENT_ASSERT> size() {3124 requireNonNull(actual, "Can not perform assertions on the size of a null iterable.");3125 return new IterableSizeAssert(this, IterableUtil.sizeOf(actual));3126 }3127 // lazy init TypeComparators3128 protected TypeComparators getComparatorsByType() {3129 if (comparatorsByType == null) comparatorsByType = defaultTypeComparators();3130 return comparatorsByType;3131 }3132 // lazy init TypeComparators3133 protected TypeComparators getComparatorsForElementPropertyOrFieldTypes() {3134 if (comparatorsForElementPropertyOrFieldTypes == null) comparatorsForElementPropertyOrFieldTypes = defaultTypeComparators();3135 return comparatorsForElementPropertyOrFieldTypes;3136 }3137 // use to build the assert instance with a filtered iterable3138 protected abstract SELF newAbstractIterableAssert(Iterable<? extends ELEMENT> iterable);3139 @SuppressWarnings({ "rawtypes", "unchecked" })3140 @Override3141 SELF withAssertionState(AbstractAssert assertInstance) {3142 if (assertInstance instanceof AbstractIterableAssert) {3143 AbstractIterableAssert iterableAssert = (AbstractIterableAssert) assertInstance;3144 return (SELF) super.withAssertionState(assertInstance).withIterables(iterableAssert.iterables)3145 .withTypeComparators(iterableAssert.comparatorsByType)3146 .withComparatorsForElementPropertyOrFieldNames(iterableAssert.comparatorsForElementPropertyOrFieldNames)3147 .withComparatorsForElementPropertyOrFieldTypes(iterableAssert.comparatorsForElementPropertyOrFieldTypes);3148 }3149 // we can go from ObjectArrayAssert -> IterableAssert when using extracting on an object array3150 if (assertInstance instanceof AbstractObjectArrayAssert) {3151 AbstractObjectArrayAssert objectArrayAssert = (AbstractObjectArrayAssert) assertInstance;3152 return (SELF) super.withAssertionState(assertInstance).withIterables(objectArrayAssert.iterables)3153 .withTypeComparators(objectArrayAssert.comparatorsByType)3154 .withComparatorsForElementPropertyOrFieldNames(objectArrayAssert.comparatorsForElementPropertyOrFieldNames)3155 .withComparatorsForElementPropertyOrFieldTypes(objectArrayAssert.comparatorsForElementPropertyOrFieldTypes);3156 }3157 return super.withAssertionState(assertInstance);3158 }3159 SELF withIterables(Iterables iterables) {3160 this.iterables = iterables;3161 return myself;3162 }3163 SELF withTypeComparators(TypeComparators comparatorsByType) {3164 this.comparatorsByType = comparatorsByType;3165 return myself;3166 }3167 SELF withComparatorsForElementPropertyOrFieldNames(Map<String, Comparator<?>> comparatorsForElementPropertyOrFieldNames) {3168 this.comparatorsForElementPropertyOrFieldNames = comparatorsForElementPropertyOrFieldNames;3169 return myself;3170 }3171 SELF withComparatorsForElementPropertyOrFieldTypes(TypeComparators comparatorsForElementPropertyOrFieldTypes) {3172 this.comparatorsForElementPropertyOrFieldTypes = comparatorsForElementPropertyOrFieldTypes;3173 return myself;3174 }3175 private SELF internalFilteredOn(Predicate<? super ELEMENT> predicate) {3176 checkArgument(predicate != null, "The filter predicate should not be null");3177 List<? extends ELEMENT> filteredIterable = stream(actual.spliterator(), false).filter(predicate).collect(toList());3178 return newAbstractIterableAssert(filteredIterable).withAssertionState(myself);3179 }3180}...

Full Screen

Full Screen

Source:AbstractObjectArrayAssert.java Github

copy

Full Screen

...2647 * @return a new assertion object with the filtered list under test2648 * @throws IllegalArgumentException if the given predicate is {@code null}.2649 */2650 public SELF filteredOn(Predicate<? super ELEMENT> predicate) {2651 return internalFilteredOn(predicate);2652 }2653 /**2654 * Filter the array under test into a list composed of the elements for which the result of the {@code function} is equal to {@code expectedValue}.2655 * <p>2656 * It allows to filter elements in more safe way than by using {@link #filteredOn(String, Object)} as it doesn't utilize introspection.2657 * <p>2658 * As an example, let's check all employees 800 years old (yes, special employees):2659 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);2660 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);2661 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);2662 * Employee noname = new Employee(4L, null, 50);2663 *2664 * Employee[] employees = new Employee[] { yoda, luke, obiwan, noname };2665 *2666 * assertThat(employees).filteredOn(Employee::getAge, 800)2667 * .containsOnly(yoda, obiwan);2668 *2669 * assertThat(employees).filteredOn(e -&gt; e.getName(), null)2670 * .containsOnly(noname);</code></pre>2671 *2672 * If you need more complex filter, use {@link #filteredOn(Predicate)} or {@link #filteredOn(Condition)}.2673 *2674 * @param <T> result type of the filter function2675 * @param function the filter function2676 * @param expectedValue the expected value of the filter function2677 * @return a new assertion object with the filtered list under test2678 * @throws IllegalArgumentException if the given function is {@code null}.2679 * @since 3.17.02680 */2681 @CheckReturnValue2682 public <T> SELF filteredOn(Function<? super ELEMENT, T> function, T expectedValue) {2683 checkArgument(function != null, "The filter function should not be null");2684 // call internalFilteredOn to avoid double proxying in soft assertions2685 return internalFilteredOn(element -> java.util.Objects.equals(function.apply(element), expectedValue));2686 }2687 /**2688 * Filter the array under test keeping only elements matching the given assertions specified with a {@link Consumer}.2689 * <p>2690 * Example : check old employees whose age &gt; 100:2691 *2692 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);2693 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);2694 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);2695 *2696 * Employee[] employees = new Employee[] { yoda, luke, obiwan };2697 *2698 * assertThat(employees).filteredOnAssertions(employee -&gt; assertThat(employee.getAge()).isGreaterThan(100))2699 * .containsOnly(yoda, obiwan);</code></pre>2700 *2701 * @param elementAssertions containing AssertJ assertions to filter on2702 * @return a new assertion object with the filtered iterable under test2703 * @throws IllegalArgumentException if the given predicate is {@code null}.2704 * @since 3.11.02705 */2706 public SELF filteredOnAssertions(Consumer<? super ELEMENT> elementAssertions) {2707 checkArgument(elementAssertions != null, "The element assertions should not be null");2708 List<ELEMENT> filteredIterable = stream(actual).filter(byPassingAssertions(elementAssertions)).collect(toList());2709 return newObjectArrayAssert(filteredIterable).withAssertionState(myself);2710 }2711 /**2712 * Verifies that all elements match the given {@link Predicate}.2713 * <p>2714 * Example :2715 * <pre><code class='java'> String[] abc = {"a", "b", "c"};2716 * String[] abcc = {"a", "b", "cc"};2717 *2718 * // assertion will pass2719 * assertThat(abc).allMatch(s -&gt; s.length() == 1);2720 *2721 * // assertion will fail2722 * assertThat(abcc).allMatch(s -&gt; s.length() == 1);</code></pre>2723 *2724 * Note that you can achieve the same result with {@link #are(Condition) are(Condition)} or {@link #have(Condition) have(Condition)}.2725 *2726 * @param predicate the given {@link Predicate}.2727 * @return {@code this} object.2728 * @throws NullPointerException if the given predicate is {@code null}.2729 * @throws AssertionError if an element cannot be cast to ELEMENT.2730 * @throws AssertionError if one or more elements don't satisfy the given predicate.2731 */2732 @Override2733 public SELF allMatch(Predicate<? super ELEMENT> predicate) {2734 iterables.assertAllMatch(info, newArrayList(actual), predicate, PredicateDescription.GIVEN);2735 return myself;2736 }2737 /**2738 * {@inheritDoc}2739 */2740 @Override2741 public SELF allMatch(Predicate<? super ELEMENT> predicate, String predicateDescription) {2742 iterables.assertAllMatch(info, newArrayList(actual), predicate, new PredicateDescription(predicateDescription));2743 return myself;2744 }2745 /**2746 * {@inheritDoc}2747 */2748 @Override2749 public SELF allSatisfy(Consumer<? super ELEMENT> requirements) {2750 iterables.assertAllSatisfy(info, newArrayList(actual), requirements);2751 return myself;2752 }2753 /**2754 * Verifies whether any elements match the provided {@link Predicate}.2755 * <p>2756 * Example :2757 * <pre><code class='java'> String[] abcc = { "a", "b", "cc" };2758 *2759 * // assertion will pass2760 * assertThat(abc).anyMatch(s -&gt; s.length() == 2);2761 *2762 * // assertion will fail2763 * assertThat(abcc).anyMatch(s -&gt; s.length() &gt; 2);</code></pre>2764 *2765 * Note that you can achieve the same result with {@link #areAtLeastOne(Condition) areAtLeastOne(Condition)}2766 * or {@link #haveAtLeastOne(Condition) haveAtLeastOne(Condition)}.2767 *2768 * @param predicate the given {@link Predicate}.2769 * @return {@code this} object.2770 * @throws NullPointerException if the given predicate is {@code null}.2771 * @throws AssertionError if no elements satisfy the given predicate.2772 * @since 3.9.02773 */2774 @Override2775 public SELF anyMatch(Predicate<? super ELEMENT> predicate) {2776 iterables.assertAnyMatch(info, newArrayList(actual), predicate, PredicateDescription.GIVEN);2777 return myself;2778 }2779 /**2780 * Verifies that the zipped pairs of actual and other elements, i.e: (actual 1st element, other 1st element), (actual 2nd element, other 2nd element), ...2781 * all satisfy the given {@code zipRequirements}.2782 * <p>2783 * This assertion assumes that actual and other have the same size but they can contain different type of elements2784 * making it handy to compare objects converted to another type, for example Domain and View/DTO objects.2785 * <p>2786 * Example:2787 * <pre><code class='java'> Adress[] addressModels = findGoodRestaurants();2788 * AdressView[] addressViews = convertToView(addressModels);2789 *2790 * // compare addressViews and addressModels respective paired elements.2791 * assertThat(addressViews).zipSatisfy(addressModels, (AdressView view, Adress model) -&gt; {2792 * assertThat(view.getZipcode() + ' ' + view.getCity()).isEqualTo(model.getCityLine());2793 * assertThat(view.getStreet()).isEqualTo(model.getStreet().toUpperCase());2794 * });</code></pre>2795 *2796 * @param <OTHER_ELEMENT> the type of the other array elements.2797 * @param other the array to zip actual with.2798 * @param zipRequirements the given requirements that each pair must satisfy.2799 * @return {@code this} assertion object.2800 * @throws NullPointerException if the given zipRequirements {@link BiConsumer} is {@code null}.2801 * @throws NullPointerException if the other array to zip actual with is {@code null}.2802 * @throws AssertionError if the array under test is {@code null}.2803 * @throws AssertionError if actual and other don't have the same size.2804 * @throws AssertionError if one or more pairs don't satisfy the given requirements.2805 * @since 3.9.02806 */2807 public <OTHER_ELEMENT> SELF zipSatisfy(OTHER_ELEMENT[] other,2808 BiConsumer<? super ELEMENT, OTHER_ELEMENT> zipRequirements) {2809 iterables.assertZipSatisfy(info, newArrayList(actual), newArrayList(other), zipRequirements);2810 return myself;2811 }2812 /**2813 * {@inheritDoc}2814 */2815 @Override2816 public SELF anySatisfy(Consumer<? super ELEMENT> requirements) {2817 iterables.assertAnySatisfy(info, newArrayList(actual), requirements);2818 return myself;2819 }2820 /**2821 * {@inheritDoc}2822 */2823 @Override2824 public SELF noneSatisfy(Consumer<? super ELEMENT> restrictions) {2825 iterables.assertNoneSatisfy(info, newArrayList(actual), restrictions);2826 return myself;2827 }2828 /**2829 * Verifies that the actual array contains at least one of the given values.2830 * <p>2831 * Example :2832 * <pre><code class='java'> String[] abc = {"a", "b", "c"};2833 *2834 * // assertions will pass2835 * assertThat(abc).containsAnyOf("b")2836 * .containsAnyOf("b", "c")2837 * .containsAnyOf("a", "b", "c")2838 * .containsAnyOf("a", "b", "c", "d")2839 * .containsAnyOf("e", "f", "g", "b");2840 *2841 * // assertions will fail2842 * assertThat(abc).containsAnyOf("d");2843 * assertThat(abc).containsAnyOf("d", "e", "f", "g");</code></pre>2844 *2845 * @param values the values whose at least one which is expected to be in the array under test.2846 * @return {@code this} assertion object.2847 * @throws NullPointerException if the array of values is {@code null}.2848 * @throws IllegalArgumentException if the array of values is empty and the array under test is not empty.2849 * @throws AssertionError if the array under test is {@code null}.2850 * @throws AssertionError if the array under test does not contain any of the given {@code values}.2851 * @since 2.9.0 / 3.9.02852 */2853 @Override2854 public SELF containsAnyOf(@SuppressWarnings("unchecked") ELEMENT... values) {2855 arrays.assertContainsAnyOf(info, actual, values);2856 return myself;2857 }2858 /**2859 * Verifies that the actual array contains at least one of the given {@link Iterable} elements.2860 * <p>2861 * Example :2862 * <pre><code class='java'> String[] abc = {"a", "b", "c"};2863 *2864 * // assertions will pass2865 * assertThat(abc).containsAnyElementsOf(Arrays.asList("b"))2866 * .containsAnyElementsOf(Arrays.asList("b", "c"))2867 * .containsAnyElementsOf(Arrays.asList("a", "b", "c"))2868 * .containsAnyElementsOf(Arrays.asList("a", "b", "c", "d"))2869 * .containsAnyElementsOf(Arrays.asList("e", "f", "g", "b"));2870 *2871 * // assertions will fail2872 * assertThat(abc).containsAnyElementsOf(Arrays.asList("d"));2873 * assertThat(abc).containsAnyElementsOf(Arrays.asList("d", "e", "f", "g"));</code></pre>2874 *2875 * @param iterable the iterable whose at least one element is expected to be in the array under test.2876 * @return {@code this} assertion object.2877 * @throws NullPointerException if the iterable of expected values is {@code null}.2878 * @throws IllegalArgumentException if the iterable of expected values is empty and the array under test is not empty.2879 * @throws AssertionError if the array under test is {@code null}.2880 * @throws AssertionError if the array under test does not contain any of elements from the given {@code Iterable}.2881 * @since 2.9.0 / 3.9.02882 */2883 @Override2884 public SELF containsAnyElementsOf(Iterable<? extends ELEMENT> iterable) {2885 return containsAnyOf(toArray(iterable));2886 }2887 /**2888 * Verifies that no elements match the given {@link Predicate}.2889 * <p>2890 * Example :2891 * <pre><code class='java'> String[] abcc = { "a", "b", "cc" };2892 *2893 * // assertion will pass2894 * assertThat(abcc).noneMatch(s -&gt; s.isEmpty());2895 *2896 * // assertion will fail2897 * assertThat(abcc).noneMatch(s -&gt; s.length() == 2);</code></pre>2898 *2899 * Note that you can achieve the same result with {@link #areNot(Condition) areNot(Condition)}2900 * or {@link #doNotHave(Condition) doNotHave(Condition)}.2901 *2902 * @param predicate the given {@link Predicate}.2903 * @return {@code this} object.2904 * @throws NullPointerException if the given predicate is {@code null}.2905 * @throws AssertionError if an element cannot be cast to ELEMENT.2906 * @throws AssertionError if any element satisfy the given predicate.2907 * @since 3.9.02908 */2909 @Override2910 public SELF noneMatch(Predicate<? super ELEMENT> predicate) {2911 iterables.assertNoneMatch(info, newArrayList(actual), predicate, PredicateDescription.GIVEN);2912 return myself;2913 }2914 /**2915 * Create a friendly soft or "hard" assertion.2916 * <p>2917 * Implementations need to redefine it so that some methods, such as {@link #extracting(Function)}, are able2918 * to build the appropriate list assert (eg: {@link ListAssert} versus {@link ProxyableListAssert}).2919 * <p>2920 * The default implementation will assume that this concrete implementation is NOT a soft assertion.2921 *2922 * @param <E> the type of elements.2923 * @param newActual new value2924 * @return a new {@link AbstractListAssert}.2925 */2926 @Override2927 protected <E> AbstractListAssert<?, List<? extends E>, E, ObjectAssert<E>> newListAssertInstance(List<? extends E> newActual) {2928 return new ListAssert<>(newActual);2929 }2930 /**2931 * Enable using a recursive field by field comparison strategy when calling the chained {@link RecursiveComparisonAssert},2932 * <p>2933 * Example:2934 * <pre><code class='java'> public class Person {2935 * String name;2936 * boolean hasPhd;2937 * }2938 *2939 * public class Doctor {2940 * String name;2941 * boolean hasPhd;2942 * }2943 *2944 * Doctor drSheldon = new Doctor("Sheldon Cooper", true);2945 * Doctor drLeonard = new Doctor("Leonard Hofstadter", true);2946 * Doctor drRaj = new Doctor("Raj Koothrappali", true);2947 *2948 * Person sheldon = new Person("Sheldon Cooper", true);2949 * Person leonard = new Person("Leonard Hofstadter", true);2950 * Person raj = new Person("Raj Koothrappali", true);2951 * Person howard = new Person("Howard Wolowitz", false);2952 *2953 * Doctor[] doctors = { drSheldon, drLeonard, drRaj };2954 * Person[] people = { sheldon, leonard, raj };2955 *2956 * // assertion succeeds as both lists contains equivalent items in order.2957 * assertThat(doctors).usingRecursiveComparison()2958 * .isEqualTo(people);2959 *2960 * // assertion fails because leonard names are different.2961 * leonard.setName("Leonard Ofstater");2962 * assertThat(doctors).usingRecursiveComparison()2963 * .isEqualTo(people);2964 *2965 * // assertion fails because howard is missing and leonard is not expected.2966 * Person[] otherPeople = { howard, sheldon, raj };2967 * assertThat(doctors).usingRecursiveComparison()2968 * .isEqualTo(otherPeople);</code></pre>2969 *2970 * A detailed documentation for the recursive comparison is available here: <a href="https://assertj.github.io/doc/#assertj-core-recursive-comparison">https://assertj.github.io/doc/#assertj-core-recursive-comparison</a>.2971 * <p>2972 * The default recursive comparison behavior is {@link RecursiveComparisonConfiguration configured} as follows:2973 * <ul>2974 * <li> different types of iterable can be compared by default, this allows to compare for example an {@code Person[]} and a {@code PersonDto[]}.<br>2975 * This behavior can be turned off by calling {@link RecursiveComparisonAssert#withStrictTypeChecking() withStrictTypeChecking}.</li>2976 * <li>overridden equals methods are used in the comparison (unless stated otherwise - see <a href="https://assertj.github.io/doc/#assertj-core-recursive-comparison-ignoring-equals">https://assertj.github.io/doc/#assertj-core-recursive-comparison-ignoring-equals</a>)</li>2977 * <li>the following types are compared with these comparators:2978 * <ul>2979 * <li>{@code java.lang.Double}: {@code DoubleComparator} with precision of 1.0E-15</li>2980 * <li>{@code java.lang.Float}: {@code FloatComparator }with precision of 1.0E-6</li>2981 * <li>any comparators previously registered with {@link AbstractIterableAssert#usingComparatorForType(Comparator, Class)} </li>2982 * </ul>2983 * </li>2984 * </ul>2985 *2986 * @return a new {@link RecursiveComparisonAssert} instance2987 * @see RecursiveComparisonConfiguration RecursiveComparisonConfiguration2988 */2989 @Override2990 @Beta2991 public RecursiveComparisonAssert<?> usingRecursiveComparison() {2992 // overridden for javadoc and to make this method public2993 return super.usingRecursiveComparison();2994 }2995 /**2996 * Same as {@link #usingRecursiveComparison()} but allows to specify your own {@link RecursiveComparisonConfiguration}.2997 * @param recursiveComparisonConfiguration the {@link RecursiveComparisonConfiguration} used in the chained {@link RecursiveComparisonAssert#isEqualTo(Object) isEqualTo} assertion.2998 *2999 * @return a new {@link RecursiveComparisonAssert} instance built with the given {@link RecursiveComparisonConfiguration}.3000 */3001 @Override3002 public RecursiveComparisonAssert<?> usingRecursiveComparison(RecursiveComparisonConfiguration recursiveComparisonConfiguration) {3003 return super.usingRecursiveComparison(recursiveComparisonConfiguration).withTypeComparators(comparatorsByType);3004 }3005 // lazy init TypeComparators3006 protected TypeComparators getComparatorsByType() {3007 if (comparatorsByType == null) comparatorsByType = defaultTypeComparators();3008 return comparatorsByType;3009 }3010 // lazy init TypeComparators3011 protected TypeComparators getComparatorsForElementPropertyOrFieldTypes() {3012 if (comparatorsForElementPropertyOrFieldTypes == null) comparatorsForElementPropertyOrFieldTypes = defaultTypeComparators();3013 return comparatorsForElementPropertyOrFieldTypes;3014 }3015 @SuppressWarnings({ "rawtypes", "unchecked" })3016 @Override3017 SELF withAssertionState(AbstractAssert assertInstance) {3018 if (assertInstance instanceof AbstractObjectArrayAssert) {3019 AbstractObjectArrayAssert objectArrayAssert = (AbstractObjectArrayAssert) assertInstance;3020 return (SELF) super.withAssertionState(assertInstance).withIterables(objectArrayAssert.iterables)3021 .withObjectArrays(objectArrayAssert.arrays)3022 .withTypeComparators(objectArrayAssert.comparatorsByType)3023 .withComparatorsForElementPropertyOrFieldNames(objectArrayAssert.comparatorsForElementPropertyOrFieldNames)3024 .withComparatorsForElementPropertyOrFieldTypes(objectArrayAssert.comparatorsForElementPropertyOrFieldTypes);3025 }3026 return super.withAssertionState(assertInstance);3027 }3028 SELF withIterables(Iterables iterables) {3029 this.iterables = iterables;3030 return myself;3031 }3032 SELF withObjectArrays(ObjectArrays arrays) {3033 this.arrays = arrays;3034 return myself;3035 }3036 SELF withTypeComparators(TypeComparators comparatorsByType) {3037 this.comparatorsByType = comparatorsByType;3038 return myself;3039 }3040 SELF withComparatorsForElementPropertyOrFieldNames(Map<String, Comparator<?>> comparatorsForElementPropertyOrFieldNames) {3041 this.comparatorsForElementPropertyOrFieldNames = comparatorsForElementPropertyOrFieldNames;3042 return myself;3043 }3044 SELF withComparatorsForElementPropertyOrFieldTypes(TypeComparators comparatorsForElementPropertyOrFieldTypes) {3045 this.comparatorsForElementPropertyOrFieldTypes = comparatorsForElementPropertyOrFieldTypes;3046 return myself;3047 }3048 // to implement to return the correct AbstractObjectArrayAssert subtype3049 protected abstract SELF newObjectArrayAssert(ELEMENT[] array);3050 /**3051 * build a new ObjectArrayAssert from the filtered list propagating the assertion state (description, comparators, ...)3052 * @param filteredList the list to convert3053 * @return a new ObjectArrayAssert3054 */3055 private SELF newObjectArrayAssert(List<ELEMENT> filteredList) {3056 ELEMENT[] filteredArray = toGenericArray(filteredList);3057 return newObjectArrayAssert(filteredArray).withAssertionState(myself);3058 }3059 // this method assumes list size < actual array.3060 @SuppressWarnings("unchecked")3061 private ELEMENT[] toGenericArray(List<ELEMENT> filteredList) {3062 // this is the only way to create a generic array:3063 // - make a copy of an existing one (actual!) to the correct size3064 // - fill the new array with some list elements3065 ELEMENT[] actualCopy = (ELEMENT[]) copyOf(actual, filteredList.size(), actual.getClass());3066 return filteredList.toArray(actualCopy);3067 }3068 private SELF internalFilteredOn(Predicate<? super ELEMENT> predicate) {3069 checkArgument(predicate != null, "The filter predicate should not be null");3070 List<ELEMENT> filteredList = stream(actual).filter(predicate).collect(toList());3071 return newObjectArrayAssert(filteredList);3072 }3073}...

Full Screen

Full Screen

internalFilteredOn

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.AbstractObjectArrayAssert;2import org.assertj.core.api.ObjectArrayAssert;3import org.assertj.core.api.ObjectArrayAssertBaseTest;4import org.assertj.core.internal.Objects;5import org.assertj.core.test.TestData;6import org.junit.Test;7import static org.mockito.Mockito.verify;8public class ObjectArrayAssert_internalFilteredOn_Test extends ObjectArrayAssertBaseTest {9 protected ObjectArrayAssert<Object> invoke_api_method() {10 return assertions.internalFilteredOn("name", "Yoda");11 }12 protected void verify_internal_effects() {13 verify(objects).assertIsNotNull("name");14 verify(objects).assertIsNotNull("Yoda");15 verify(objects).assertIsNotNull(getInfo(assertions), getActual(assertions));16 verify(objects).assertIsInstanceOf(getInfo(assertions), getActual(assertions), Object[].class);17 verify(objects).assertHasSize(getInfo(assertions), getActual(assertions), 3);18 verify(objects).filter(getInfo(assertions), getActual(assertions), "name", "Yoda");19 }20}21import org.assertj.core.api.AbstractObjectArrayAssert;22import org.assertj.core.api.ObjectArrayAssert;23import org.assertj.core.api.ObjectArrayAssertBaseTest;24import org.assertj.core.internal.Objects;25import org.assertj.core.test.TestData;26import org.junit.Test;27import static org.mockito.Mockito.verify;28public class ObjectArrayAssert_internalFilteredOn_Test extends ObjectArrayAssertBaseTest {29 protected ObjectArrayAssert<Object> invoke_api_method() {30 return assertions.internalFilteredOn("name", "Yoda");31 }32 protected void verify_internal_effects() {33 verify(objects).assertIsNotNull("name");34 verify(objects).assertIsNotNull("Yoda");35 verify(objects).assertIsNotNull(getInfo(assertions), getActual(assertions));36 verify(objects).assertIsInstanceOf(getInfo(assertions), getActual(assertions), Object[].class);37 verify(objects).assertHasSize(getInfo(assertions), getActual(assertions), 3);38 verify(objects).filter(getInfo(assertions), getActual(assertions), "name", "Yoda");39 }40}41import org.assertj.core.api.Abstract

Full Screen

Full Screen

internalFilteredOn

Using AI Code Generation

copy

Full Screen

1import org.junit.Test;2import org.junit.runner.RunWith;3import org.junit.runners.JUnit4;4import static org.assertj.core.api.Assertions.assertThat;5@RunWith(JUnit4.class)6public class 1 {7 public void test1() {8 String[] array = {"a", "b", "c"};9 assertThat(array).internalFilteredOn((s) -> s.equals("a")).contains("a");10 }11}12at org.assertj.core.error.ShouldContain.shouldContain(ShouldContain.java:60)13at org.assertj.core.internal.Failures.failure(Failures.java:90)14at org.assertj.core.internal.Failures.failure(Failures.java:76)15at org.assertj.core.internal.ObjectArrays.assertContains(ObjectArrays.java:79)16at org.assertj.core.api.AbstractObjectArrayAssert.internalFilteredOn(AbstractObjectArrayAssert.java:205)17at 1.test1(1.java:12)

Full Screen

Full Screen

internalFilteredOn

Using AI Code Generation

copy

Full Screen

1import org.junit.Test;2import org.junit.runner.RunWith;3import org.mockito.junit.MockitoJUnitRunner;4import java.util.function.Predicate;5import static org.assertj.core.api.Assertions.assertThat;6import static org.assertj.core.api.Assertions.assertThatThrownBy;7@RunWith(MockitoJUnitRunner.class)8public class InternalFilteredOnMethodTest {9 public void testInternalFilteredOn() {10 String[] stringArray = {"a", "b", "c", "d"};11 Predicate<String> predicate = s -> s.equals("a") || s.equals("b");12 assertThat(stringArray).internalFilteredOn(predicate).containsExactly("a", "b");13 }14 public void testInternalFilteredOn_ThrowException() {15 String[] stringArray = {"a", "b", "c", "d"};16 Predicate<String> predicate = s -> s.equals("a") || s.equals("b");17 assertThatThrownBy(() -> assertThat(stringArray).internalFilteredOn(predicate).containsExactly("a", "b", "c"))18 .isInstanceOf(AssertionError.class)19 .hasMessageContaining("Expecting array to contain exactly [a, b, c] elements, but found [a, b]");20 }21}

Full Screen

Full Screen

internalFilteredOn

Using AI Code Generation

copy

Full Screen

1import static org.assertj.core.api.Assertions.*;2import org.assertj.core.api.AbstractObjectArrayAssert;3public class 1 {4 public static void main(String[] args) {5 Object[] array = new Object[] { "a", "b", "c" };6 AbstractObjectArrayAssert<?, Object[]> assertion = assertThat(array);7 assertion.internalFilteredOn(new Predicate<Object>() {8 public boolean test(Object o) {9 return true;10 }11 });12 }13}14import static org.assertj.core.api.Assertions.*;15import org.assertj.core.api.AbstractObjectArrayAssert;16public class 2 {17 public static void main(String[] args) {18 Object[] array = new Object[] { "a", "b", "c" };19 AbstractObjectArrayAssert<?, Object[]> assertion = assertThat(array);20 assertion.internalFilteredOn(new Predicate<Object>() {21 public boolean test(Object o) {22 return true;23 }24 });25 }26}27import static org.assertj.core.api.Assertions.*;28import org.assertj.core.api.AbstractObjectArrayAssert;29public class 3 {30 public static void main(String[] args) {31 Object[] array = new Object[] { "a", "b", "c" };32 AbstractObjectArrayAssert<?, Object[]> assertion = assertThat(array);33 assertion.internalFilteredOn(new Predicate<Object>() {34 public boolean test(Object o) {35 return true;36 }37 });38 }39}40import static org.assertj.core.api.Assertions.*;41import org.assertj.core.api.AbstractObjectArrayAssert;42public class 4 {43 public static void main(String[] args) {44 Object[] array = new Object[] { "a", "b", "c" };45 AbstractObjectArrayAssert<?, Object[]> assertion = assertThat(array);46 assertion.internalFilteredOn(new Predicate<Object>() {47 public boolean test(Object o) {48 return true;49 }50 });51 }52}53import static org.assertj.core.api.Assertions.*;54import org.assertj.core.api.AbstractObjectArrayAssert;

Full Screen

Full Screen

internalFilteredOn

Using AI Code Generation

copy

Full Screen

1package org.assertj.core.api.objectarray;2import org.assertj.core.api.AbstractObjectArrayAssert;3import org.assertj.core.api.Assertions;4import org.assertj.core.api.ObjectArrayAssert;5public class InternalFilteredOnDemo {6 public static void main(String[] args) {7 String[] arr = { "abc", "def", "ghi", "jkl" };8 ObjectArrayAssert<String> objectArrayAssert = Assertions.assertThat(arr);9 AbstractObjectArrayAssert<?, String> abstractObjectArrayAssert = objectArrayAssert.internalFilteredOn(s -> s.startsWith("d"));10 abstractObjectArrayAssert.contains("def");11 }12}13 at org.junit.Assert.assertEquals(Assert.java:115)14 at org.junit.Assert.assertEquals(Assert.java:144)15 at org.assertj.core.api.AbstractObjectArrayAssertTest.internalFilteredOn(AbstractObjectArrayAssertTest.java:73)16 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)17 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)18 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)19 at java.lang.reflect.Method.invoke(Method.java:498)20 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)21 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)22 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)23 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)24 at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)25 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)26 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)27 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)28 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)29 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)30 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)31 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)32 at org.junit.runners.ParentRunner.run(ParentRunner.java:363)

Full Screen

Full Screen

internalFilteredOn

Using AI Code Generation

copy

Full Screen

1package org.assertj.core.api.objectarray;2import org.assertj.core.api.AbstractObjectArrayAssert;3public class ObjectArrayAssert_filteredOn_Test {4 public static void main(String[] args) {5 AbstractObjectArrayAssert<?, ?> arrayAssert = new ObjectArrayAssert(new Object[] {"a", "b", "c"});6 arrayAssert.internalFilteredOn("a");7 }8}9Exception in thread "main" java.lang.NoSuchMethodError: org.assertj.core.api.AbstractObjectArrayAssert.internalFilteredOn(Ljava/lang/Object;)Lorg/assertj/core/api/AbstractObjectArrayAssert;10assertThat(new Object[] {"a", "b", "c"}).filteredOn("a");

Full Screen

Full Screen

internalFilteredOn

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.AbstractObjectArrayAssert;2import org.assertj.core.api.Assertions;3import org.assertj.core.api.Condition;4import org.assertj.core.api.TestCondition;5import org.junit.Test;6public class InternalFilteredOnTest {7 public void test() {8 AbstractObjectArrayAssert<?, ?> obj = Assertions.assertThat(new Integer[] { 1, 2, 3 });9 Condition<Integer> condition = new TestCondition<>();10 obj.internalFilteredOn(condition);11 }12}13Exception in thread "main" java.lang.NoSuchMethodError: org.assertj.core.api.AbstractObjectArrayAssert.internalFilteredOn(Lorg/assertj/core/api/Condition;)Lorg/assertj/core/api/AbstractObjectArrayAssert;14 at InternalFilteredOnTest.test(InternalFilteredOnTest.java:15)15 at InternalFilteredOnTest.main(InternalFilteredOnTest.java:7)

Full Screen

Full Screen

internalFilteredOn

Using AI Code Generation

copy

Full Screen

1import static org.assertj.core.api.Assertions.assertThat;2import org.junit.Test;3public class 1 {4 public void test() {5 Integer[] arr = { 1, 2, 3, 4, 5 };6 assertThat(arr).internalFilteredOn(i -> i % 2 == 0).containsExactly(2, 4);7 }8}9import static org.assertj.core.api.Assertions.assertThat;10import java.util.Arrays;11import java.util.List;12import org.junit.Test;13public class 2 {14 public void test() {15 List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);16 assertThat(list).internalFilteredOn(i -> i % 2 == 0).containsExactly(2, 4);17 }18}19import static org.assertj.core.api.Assertions.assertThat;20import java.util.Arrays;21import java.util.List;22import org.junit.Test;23public class 3 {24 public void test() {25 List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);26 assertThat(list).internalFilteredOn(i -> i % 2 == 0).containsExactly(2, 4);27 }28}29import static org.assertj.core.api.Assertions.assertThat;30import java.util.HashMap;31import java.util.Map;32import org.junit.Test;33public class 4 {34 public void test() {35 Map<Integer, String> map = new HashMap<>();36 map.put(1, "one");37 map.put(2, "two");38 map.put(3, "three");39 assertThat(map).internalFilteredOn((k, v) -> k % 2 == 0).containsOnlyKeys(2);40 }41}42import static org.assertj.core.api.Assertions.assertThat;43import java.util.Arrays;44import java.util.List;45import org.junit.Test;46public class 5 {47 public void test() {

Full Screen

Full Screen

internalFilteredOn

Using AI Code Generation

copy

Full Screen

1package com.mycompany.app;2import org.assertj.core.api.AbstractObjectArrayAssert;3public class App {4 public static void main(String[] args) {5 AbstractObjectArrayAssert<?, ?> obj = null;6 obj.internalFilteredOn(null, null);7 }8}9package com.mycompany.app;10import org.assertj.core.api.AbstractIterableAssert;11public class App {12 public static void main(String[] args) {13 AbstractIterableAssert<?, ?> obj = null;14 obj.internalFilteredOn(null, null);15 }16}

Full Screen

Full Screen

internalFilteredOn

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.Assertions;2public class AssertJTest {3 public static void main(String[] args) {4 String[] stringArray = {"one", "two", "three", "four"};5 Assertions.assertThat(stringArray).internalFilteredOn(obj -> obj.toString().length() > 3).contains("three");6 }7}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Assertj automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in AbstractObjectArrayAssert

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful