Search code examples
junittestngtestng-eclipse

Mocking a hashmap in testng


I'm writing a test case for below method

protected Map<String, Integer> getColumnToIndexMap(String[] columns) {
        Map<String, Integer> columnToIndexMap = Maps.newHashMap();
        for (int i = 0; i < columns.length; i++) {
            columnToIndexMap.put(columns[i], i);
        }
        return columnToIndexMap;
       }

Please let me know if the test case is correct

   @Test
   public void getColumnToIndexMapTest() {
     String[] columns = {"Item1","Item2"};
     Map<String, Integer> columnToIndexMap = Maps.newHashMap();
     for (int i = 0; i < columns.length; i++) {
       columnToIndexMap.put(columns[i], i);
   }
   Assert.assertTrue(columnToIndexMap.containsKey("Item2"));
   Assert.assertEquals(columnToIndexMap.get("Item2"), "1");
  }

Solution

  • Your method under test is returning a map populated with few entries. But your Junit test is not invoking that method. Consider the case when method body of getColumnToIndexMap() gets changed over time, do you think that your test cases will still apply?

    What if getColumnToIndexMap() employs deletion of some entries too, will your test cover deletion checking too? No, unless you continuously keep the code in Junit in sync with the tested method. That is high on maintenance and never recommended.