Junit : Mocking a method of spy

Vinodhini Chockalingam
1 min readJan 8, 2019

--

I came across a test case failure in my project. The method mocked using spy was something like

public class Service { 
public String foo() {
return "dummy";
}
}

And in the test cases

private Service spyService; @Test public void test() {
String test = "test";
when(spyService.foo()).thenReturn(test);
}

We did some changes in the Service to cache the reference values during initialization and use the map to get the values.

public class Service { 
private Map cache; ...
public String foo() {
return cache.get("someKey");
}
}

And now the test cases started throwing NPE at cache.get() in Service’s foo Why is this? When you use spy, the method actually gets called. That’s why before adding the cache, it was working fine. So when you are using when on spy, call doReturn first. This will prevent the method being mocked from getting executed.

doReturn(test).when(spyService).foo();

Read this for more details. Be careful when using spy in junit tests.

Originally published at cheeky-chinnu.blogspot.com on January 8, 2019.

--

--

Vinodhini Chockalingam
Vinodhini Chockalingam

Written by Vinodhini Chockalingam

Not a blogger. I mostly move my well-written notes here.

No responses yet