Jack
Jack

Reputation: 6620

How to mock a method that is expected to return HashMap?

I have a method that is expected to return a result of type HashMap, and I need to unit test it. The method is supposed to receive a string and show the occurrence of each three characters.

public HashMap<String,Integer> findOccurences(String myStr){
    return null;
}

I need to know how can I write the unit test for it using Mockito.

public class TestMySubString {
    @Mock
    private static MySubString mockedMySub;
    private static String str;
    private static HashMap<String,Integer> result;

    @BeforeClass
    public static void setUp(){
        str = "This This"; 
        result.put(" Th", 1);
        result.put("s T",1); 
        result.put("his",2);
        result.put("Thi ",2);
        result.put("is ",1);
        when(mockedMySub.findOccurences(str)).thenReturn(result);
    }

    @Test
    public void testFindOccurences() {
        HashMap<String,Integer> myResult = mockedMySub.findOccurences(str);
        //assertReflectionEquals(result,myResult);
    }

based on this question I used assertReflectionEquals but it still returns an error.

Upvotes: 3

Views: 11746

Answers (1)

ZeroOne
ZeroOne

Reputation: 3171

If you are trying to do TDD, you are getting it wrong. You should ^1:

  1. add a test
  2. run all the tests, see if the new one fails
  3. write some code
  4. run tests
  5. refactor
  6. repeat

Plain and simple, this is what you want. No mocks or anything:

public class MySubStringTest {
private MySubString mySubString = new MySubString();

@Test
public void testFindOccurences() {
    final Map<String,Integer> myResult = mySubString.findOccurences("This This");
    final Map<String, Integer> expected = new HashMap<String, Integer>() {
        {
            put("Thi", 2);
            put("his", 2);
            put("is ", 1);
            // etc
        }
    };
    assertEquals(expected, myResult);
}
}

After you've got this in place you have completed step 1 of the list that's above. Run it and see it fail (step 2), then write an implementation for your method (step 3), etc.

You should use mocking when your method being tested has external dependencies. For example, you have a method public String getWeather() that returns "It's hot!" or "It's cold!", based on a call to an external web API for the weather in some location. Then you'd mock the weather API component to return that it's -12 degrees Centigrade and you assert that the result of your method is "It's cold!". Then in the next test you mock the external API component to return that it's +38 degrees Centigrade and assert that your method returns "It's hot!".

Upvotes: 4

Related Questions