munHunger
munHunger

Reputation: 2999

Mock object to run different void method

I am trying to write testcases for a method I've implemented that in turn uses a third party cache provider. The problem I am facing is that the cache is asyncronous, making it quite hard to test since the element put into cache are not instantly in the cache.

My solution to this was to just mock the cache using PowerMockito. I can make it so that it always returns the same object, but preferable I want it to put the object into a HashMapon put and get it from the same map on a get operation. The get operation should be pretty simple, something like:

    final Map<String, Object> cacheMap = new HashMap<>();
    Answer<Object> getFunction = invocation ->  
            cacheMap.get(invocation.getArgument(0));
    when(mockCache.get(any())).thenAnswer(getFunction);

But I am not sure how to mock a similar call for the void method mockCache.put(any(), any()) It atleast seems as if you cannot mock void functions to anything other than calling the real method or doing nothing.

Upvotes: 0

Views: 102

Answers (1)

hecko84
hecko84

Reputation: 1324

I think you are looking for intercepting the original call and rerouting it to a different implementation. Have a look at this answer for an explanation how to do it.

Upvotes: 1

Related Questions