Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Hamcrest matcher that checks if the string is as expected, ignoring line order.
import java.util.Arrays;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
public class StringIsEqualIgnoringLineOrder extends TypeSafeMatcher<String> {
private final String expected;
private final String[] expectedLines;
private StringIsEqualIgnoringLineOrder(String expected) {
this.expected = expected;
expectedLines = expected.split("\r?\n");
Arrays.sort(expectedLines);
}
@Override
public void describeTo(Description description) {
description.appendText("a string (ignoring line order) ").appendValue(expected);
}
@Override
protected boolean matchesSafely(String actual) {
String[] actualLines = actual.split("\r?\n");
Arrays.sort(actualLines);
return Arrays.equals(expectedLines, actualLines);
}
/** Creates a matcher that checks if the string is as expected, ignoring line order. */
public static Matcher<String> equalToIgnoringLineOrder(String expected) {
return new StringIsEqualIgnoringLineOrder(expected);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment