I use Mockito and JUnit 5. I have a small program that counts distinct characters in a string. I have a cache in the form of a Map and the result is picked from the cache if the input string had been processed before. My goal is to write a test using Mockito to verify that the result is picked from the cache if the string had been processed before. I can't figure out how to use the verify Mockito method properly. Here is my code:
public class CounterDecorator implements CharCounter{
Cache cache;
CharCounter counter;
public CounterDecorator(Cache cache, CharCounter counter) {
this.cache = cache;
this.counter=counter;
}
@Override
public Map<Character, Integer> count(String text) {
if(!cache.contains(text)) {
System.out.println("New entry in cache");
cache.putText(text, counter.count(text));
}
return cache.getText(text);
}
}
public class Cache {
private Map <String, Map<Character, Integer>> cache = new HashMap <>();
public void putText(String text, Map <Character, Integer> result) {
cache.put(text, result);
}
public Map<Character, Integer> getText(String text) {
return cache.get(text);
}
public boolean contains(String text) {
return cache.containsKey(text);
}
}
And tests:
@ExtendWith(MockitoExtension.class)
class DecoratorTest {
@Mock
Cache mcache;
@Mock
CharCounter mcharcounter;
@InjectMocks
CounterDecorator decorator;
@Test
void testWhenCacheIsNotEmpty() {
Map<Character, Integer> testMap = Collections.emptyMap();
verify(mcache, atLeastOnce()).putText("some string", testMap);
}
}
I am sure I use Mockito wrong. But I can't figure out how to resolve my problem. Thank you in advance.
EDIT. I edited my tests part a bit: removed that confusing map instantiation.