gpt4 book ai didi

java - 我使用了 doReturn,为什么 Mockito 仍然会在匿名类中调用真正的实现?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:52:37 27 4
gpt4 key购买 nike

我要测试的类:

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

最佳答案

这归结为 spy 的实现。根据docs , spy 被创建为真实实例的副本:

Mockito does not delegate calls to the passed real instance, instead it actually creates a copy of it. So if you keep the real instance and interact with it, don't expect the spied to be aware of those interaction and their effect on real instance state. The corollary is that when an unstubbed method is called on the spy but not on the real instance, you won't see any effects on the real instance.

这似乎是一个副本。结果,据我的调试显示,CacheLoader 在副本和原始对象之间共享,但它对其封闭对象的引用是原始对象,而不是 spy 。因此,真正的 retrieveValue 被调用而不是模拟的。

我不确定解决这个问题的最佳方法是什么。这个特定示例的一种方法是反转 CacheLoader 依赖项(即将其传递到 Subject 而不是 Subject 内部定义它),并模拟而不是 Subject

关于java - 我使用了 doReturn,为什么 Mockito 仍然会在匿名类中调用真正的实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32218312/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com