Last active
May 2, 2020 18:45
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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