I am writing test cases for this code.
But I am not able to write junit test cases for this. I am having problem to write junit test cases for this.
Please help to write mockito or junit test case for this.
public class BasicCacheManager implements CacheManager {
private ConcurrentHashMap<String, BasicCache> cacheMap;
private String defaultCache;
public BasicCacheManager() {
this.cacheMap = new ConcurrentHashMap<String, BasicCache>();
}
public BasicCacheManager(List<String> cacheNames) {
this.cacheMap = new ConcurrentHashMap<String, BasicCache>();
addCache(cacheNames);
}
@Override
public BasicCache getCache(){
return getCache(defaultCache);
}
@Override
public BasicCache getCache(String name) {
return cacheMap.get(name);
};
@Override
public void addCache(BasicCache cache) {
cacheMap.put(cache.getName(), cache);
};
@Override
public void removeCache(String name) {
cacheMap.remove(name);
};
@Override
public void removeAll() {
cacheMap = new ConcurrentHashMap<String, BasicCache>();
};
@Override
public boolean cacheExists(String name) {
return cacheMap.containsKey(name);
};
@Override
public void removeElement(String cacheName, String element){
BasicCache cache = getCache(cacheName);
if(cache != null){
cache.remove(element);
}
}
// added final to avoid any child classes from overriding this method
private final void addCache(List<String> cacheNames) {
for (String cacheName : cacheNames) {
BasicCache cache = new BasicCache(cacheName);
addCache(cache);
}
}
}
You don't need mocking here.
Your CUT (class under test) has very clear semantics; and interfaces that basically guide you into writing testcases. What you have to do: create objects of your cache class; and then use its methods to modify it; and asserts to verify.
Example:
@Test
public void testNewCacheIsEmpty() {
BasicCache underTest = new BasicCache();
assertThat(underTest.isEmpty(), is(true));
}
(in case you dont have an isEmpty() yet, you could add that one as package-protected method; just to allow for such tests).
Then you write other tests; for example that make sure that adding a certain cache-key ... actually does what you expect that to do.
So, the primary thing to understand here: you should design your whole cache so that you can test it ... without knowing what exactly it is doing.
Of course, you could create a mocked ConcurrentHashMap object and pass that into your class; to verify that exactly those calls that you expect for some operation to take place really happen. But that means: testing implementation details. And you want to avoid that if possible.
And just for the record: your field defaultCache doesn't make any sense in the code you are showing. It is null initially, there is no setter for it; so it has absolutely no purpose.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.