0

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.

FarFarAway
  • 1,017
  • 3
  • 14
  • 35
  • Where is the ordering code? And where have you invoked it in the test? Your test as of now simply creates a list and asserts it, it would definitely pass as per the matcher logic you've given – Vasan Oct 28 '16 at 05:32
  • Use `if(item.get(i).compareTo(item.get(i+1)) < 0) return false;` to check for ordering. – 4castle Oct 28 '16 at 05:38

2 Answers2

2

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!

GhostCat
  • 137,827
  • 25
  • 176
  • 248
1

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);
     }
Vasu
  • 21,832
  • 11
  • 51
  • 67