Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AssertJ Java: multiple conditions assertion

is it possible to write in Java AssertJ multi-conditions assertion which will pass if at least one of conditions met? (similar to OR operator)

I want something like this:

assertThat(listOfStrings)
           .satisfiesAnyOf(
                 a -> Assertions.assertThat(listItem).matches(someRegex),
                 // OR
                 b -> Assertions.assertThat(listItem).equals(someString)
            );

Assertion which will receive List of strings and will check each element of list against Regex and equals another string, all elements of list should satisfy at least one of conditions, and in that case - assertion should pass.

Any help greatly appreciated!

Tried a lot of options but none of them works perfectly.

like image 975
Konstantinas.A Avatar asked Feb 28 '26 20:02

Konstantinas.A


1 Answers

here we are. you can fit contains and matchesRegex methods in variables, as you like !

package org.example.test;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.function.Predicate;
import java.util.regex.Pattern;

import static org.assertj.core.api.Assertions.assertThat;

public class MultipleConditionsTest {
    @Test
    public void test() {
        // Given
        String someString = "", regex = "";
        // When
        ArrayList<String> actual = new ArrayList<>();
        // Then
        assertThat(actual)
                .anyMatch(contains(someString).or(matchesRegex(regex)));
    }

    private static Predicate<? super String> matchesRegex(String regex) {
        return string ->Pattern.compile(regex).matcher(string).matches();

    }

    private static Predicate<String> contains(String someString) {
        return string -> string.equalsIgnoreCase(someString);
    }
}

that you can combine as you wish, like this

@Test
public void containsOrMatchesRegexTest() {
    // Given
    // When
    List<String> fruits = Arrays.asList("banana", "apple", "orange");
    // Then
    assertThat(fruits)
            .as("At least one element should contain 'raspberry' or match the regex 'a.+?'")
            .anyMatch(contains("raspberry").or(matchesRegex("a.+?")))
            .as("At least one element should contain 'banana' or match the regex 'p.+?'")
            .anyMatch(contains("banana").or(matchesRegex("p.+?")))
            .as("No element should contain 'blueberry' or match the regex '.+?c.+?'")
            .noneMatch(contains("blueberry").or(matchesRegex(".+?c.+?")))
    ;
}
like image 120
Stefano Riffaldi Avatar answered Mar 03 '26 09:03

Stefano Riffaldi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!