Skip to content

Instantly share code, notes, and snippets.

@kevinlin1
Last active May 2, 2020 18:45
Show Gist options
  • Save kevinlin1/dd74e27a2a094c4d550ccdf97c0459c8 to your computer and use it in GitHub Desktop.
Save kevinlin1/dd74e27a2a094c4d550ccdf97c0459c8 to your computer and use it in GitHub Desktop.
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