Issue
so, I have method:
public List<Map.Entry<String, Integer>> sortMap(HashMap<String, Integer> map) {
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
list.sort((o1, o2) -> {
int value = o2.getValue().compareTo(o1.getValue());
if (value != 0) {
return value;
}
return o1.getKey().compareTo(o2.getKey());
});
return list;
}
I need a JUnit test for him. Actually, I started code it, but i dont know how to finish it right
@Test
public void shouldReturnCurrentList() {
Object object = new Object();
List<Map.Entry<String, Integer>> testList = new ArrayList<>(testMap.entrySet());
testMap.put("One", 1);
testMap.put("Two", 2);
testMap.put("Three", 3);
testMap.put("Four", 4);
object.sortMap(testMap);
}
Solution
Create the Map. In this case I'm adding an element that has a duplicated value.
Map<String,Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
map.put("Four", 4);
map.put("AnotherFour", 4);
Now invoke the method
List<Map.Entry<String, Integer>> actual = SUT.sortMap(map);
Now test the order based on how we expect the Map to be processed. For out map, the order of the keys should be "One", "Two", "Three", "AnotherFour", "Four" and the order of the values should be 1, 2, 3, 4, 4.
Assert.assertEquals("One", actual.get(0).getKey());
Assert.assertEquals(1, actual.get(0).getValue());
Assert.assertEquals("Two", actual.get(1).getKey());
Assert.assertEquals(2, actual.get(1).getValue());
Assert.assertEquals("Three", actual.get(2).getKey());
Assert.assertEquals(3, actual.get(2).getValue());
Assert.assertEquals("AnotherFour", actual.get(3).getKey());
Assert.assertEquals(4, actual.get(3).getValue());
Assert.assertEquals("Four", actual.get(4).getKey());
Assert.assertEquals(4, actual.get(4).getValue());
Answered By - vsfDawg
Answer Checked By - Cary Denson (JavaFixing Admin)