Home > Net >  Mocking generics and wild card with mockito
Mocking generics and wild card with mockito

Time:07-04

I have a class that uses wild cards and generics to return a cache object and I'm trying to mock it but I get the following error:

Unfinished stubbing detected here:
-> at com.demo.MyTestTest.initTests(MyTest.java:232)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();

my generic class is:

public class AsyncCaffeineCacheManager {
    private final Map<String, AsyncCache<?, ?>> cacheMap;
    @Getter
    private final List<String> cacheNames;

    private AsyncCaffeineCacheManager(Map<String, AsyncCache<?, ?>> cacheMap, List<String> cacheNames) {
        this.cacheMap = cacheMap;
        this.cacheNames = cacheNames;
    }

    @SuppressWarnings("unchecked")
    public <K, V> AsyncCache<K, V> getCache(String cacheName) {
        return (AsyncCache<K, V>) cacheMap.get(cacheName);
    }

    ......
}

and my test class:

public class MyTest {
    @BeforeEach
    public void initTests() {
        doReturn(new NoOpAsyncCache<Integer, MyValue>("cacheName"))
                .when(asyncCaffeineCacheManager.getCache(anyString()));
    }
}

I also created a NoOpAsyncCache which is default implementation:

@Getter
public class NoOpAsyncCache<K, V> implements AsyncCache<K, V> {
    private final String cacheName;

    public NoOpAsyncCache(String cacheName) {
        this.cacheName = cacheName;
    }
    @Override
    public @Nullable CompletableFuture<V> getIfPresent(K key) {
        return null;
    }

    @Override
    public CompletableFuture<V> get(K key, Function<? super K, ? extends V> mappingFunction) {
        return null;
    }

    @Override
    public CompletableFuture<V> get(K key, BiFunction<? super K, ? super Executor, ? extends CompletableFuture<? extends V>> mappingFunction) {
        return null;
    }

   ......
}

I also tried to create a real one, but it didn't work.

Would love to hear some ideas.

CodePudding user response:

Turns out it was not an issue with generics. the when(..) was wrong: instead of:

 .when(asyncCaffeineCacheManager.getCache(anyString()));

it should have been:

 .when(asyncCaffeineCacheManager).getCache(anyString());

also NoOpAsyncCache didn't work well for me, had to use a real implementation

 doReturn(Caffeine.newBuilder().buildAsync())
                .when(asyncCaffeineCacheManager).getCache(anyString());
  • Related