-2

Say I have a list of apple "listOfApples".

class apple {
    int serial;
    int price;
    ......
}

Multiple apple may have same serial. I have to make sure that all the apples in listOfApples are sorted based on their serial.
More precisely all apples from listOfApples that have serial 0 are in the front of the list.
How can I test listOfApples whether it keep the apple in order or not using junit ?

neelrotno
  • 159
  • 2
  • 8
  • Have you actually tried anything? What happened? Give a [mcve]. – jonrsharpe Mar 21 '17 at 06:44
  • And read about java coding conventions. Class names start upper case. And yes, your question is really missing key information. Please spend some time at the [help] to learn how things work here. Definitely not like this. – GhostCat Mar 21 '17 at 08:33

2 Answers2

2

This seems relatively straightforward - just test that the list is the same before and after it has been sorted:

List<Apple> sortedApples = new ArrayList<>(listOfApples);
sortedApples.sort(Comparator.comparingInt(a -> a.serial));
assertEquals(sortedApples, listOfApples);

If the two lists are equal then the original list was correctly sorted.

Addition:

Good pickup by @Harmlezz in the comments: this test could fail even though the original list is correctly sorted. An alternative is:

assertTrue(IntStream.range(1, sortedAppples.size())
    .allMatch(i -> sortedApples.get(i).serial >= sortedApples.get(i-1).serial));
sprinter
  • 27,148
  • 6
  • 47
  • 78
  • This is the way to go. A `List` is equal to another `List` if it contains the same items in the same order. See https://docs.oracle.com/javase/7/docs/api/java/util/List.html#equals(java.lang.Object) – Matt Mar 21 '17 at 07:13
  • Thanks friend @sprinter. Seems to me it'll work. I'll check it and obviously inform you. – neelrotno Mar 21 '17 at 07:25
  • 1
    as I mentioned in my answer, apples having the same serial may appear at different positions in the list after sorting which may result in the test to fail. – Harmlezz Mar 21 '17 at 08:36
  • @sprinter: now I like your second solution more than mine :-) It even works for the case, when `sortedApples` is empty. – Harmlezz Mar 22 '17 at 07:12
1

Due to the fact that apples may have the same serial, you can't rely on sorting of lists, because apples having the same serial may appear at unpredictable positions: Hence try:

@Test
public void testOrderingOfProvidedApples() {
    int serial = Integer.MIN_VALUE;
    for (Apple apple : listOfApples()) {
        assertTrue(apple.getSerial() >= serial);
        serial = apple.getSerial();
    }
}
Harmlezz
  • 7,972
  • 27
  • 35