I came across a test case failure in my project. The method mocked using spy was something like
And in the test cases
We did some changes in the Service to cache the reference values during initialization and use the map to get the values.
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.
Read this for more details.
Be careful when using spy in junit tests.
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 MapAnd now the test cases started throwing NPE at cache.get() in Service's foocache; ... public String foo() { return cache.get("someKey"); } }
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.
No comments:
Post a Comment