我用了 doReturn,为什么 Mockito 仍然会在匿名类中调用真正的实现?
我要测试的类:
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
public class Subject {
private CacheLoader<String, String> cacheLoader = new CacheLoader<String, String>() {
@Override
public String load(String key)
throws Exception {
return retrieveValue(key);
}
};
private LoadingCache<String, String> cache = CacheBuilder.newBuilder()
.build(cacheLoader);
public String getValue(String key) {
return cache.getUnchecked(key);
}
String retrieveValue(String key) {
System.out.println("I should not be called!");
return "bad";
}
}
这是我的测试用例
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doReturn;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class SubjectTest {
String good = "good";
@Spy
@InjectMocks
private Subject subject;
@Test
public void test() {
doReturn(good).when(subject).retrieveValue(anyString());
assertEquals(good, subject.getValue("a"));
}
}
我得到了
org.junit.ComparisonFailure:
Expected :good
Actual :bad