Reputation: 1115
I hava a list of strings and in my code I order this list. I want to write a unit test to ensure that the list has been orderer properly. my code
@Test
public void test() {
List<String> orderedList = new ArrayList<String>();
orderedList.add("a");
orderedList.add("b");
orderedList.add("a");
assertThat(orderedList, isInDescendingOrdering());
}
private Matcher<? super List<String>> isInDescendingOrdering()
{
return new TypeSafeMatcher<List<String>>()
{
@Override
public void describeTo (Description description)
{
description.appendText("ignored");
}
@Override
protected boolean matchesSafely (List<String> item)
{
for(int i = 0 ; i < item.size() -1; i++) {
if(item.get(i).equals(item.get(i+1))) return false;
}
return true;
}
};
}
somehow it success al the times.
Upvotes: 0
Views: 1793
Reputation: 22442
You can do it simply by copying the array, then sorting it and finally compare it with original array.
The code is given below:
@Test
public void test() {
List<String> orderedList = new ArrayList<String>();
orderedList.add("a");
orderedList.add("b");
orderedList.add("a");
//Copy the array to sort and then to compare with original
List<String> orderedList2 = new ArrayList<String>(orderedList);
orderedList2.sort((String s1, String s2) -> s1.compareTo(s2));
Assert.assertEquals(orderedList, orderedList2);
}
Upvotes: 1
Reputation: 140553
You are absolutely overcomplicating things here. Writing a custom matcher is a nice exercise, but it does not add any real value to your tests.
Instead I would suggest that you simply create some
String[] expectedArray =....
value and give that to your call to assertThat. That is less sexy, but much easier to read and understand. And that is what counts for unit tests!
Upvotes: 2