![](/img/trans.png)
[英]Mockito is not mocking the object instead its calling the method inside the object
[英]Mockito when is not mocking instead of calling actual method
我正在尝试模拟 Java 类。
我的测试班,
@RunWith(MockitoJunitRunner.class)
public class ATest {
@Test
public void readContent() throws Exception {
Map<String, String> params = new HashMap<>();
params.put("key", "value");
C c = Mockito.mock(C.class);
when(c.methodCall("myString")).thenReturn(params);
String response = A.readParams("anyString");
}
}
public class A{
private A(){
}
public static String readParams(anyString){
C c = new C();
Map<String, String> map = c.methodCall("myString");
return "returnString";
}
}
这里,
Map<String, String> map = c.methodCall("myString");
这条线不是在嘲笑。 而不是它调用实际方法。
我正在使用以下罐子,
我该如何调查这个问题?
问题是您正在模拟 C,并且在 readParams 方法中创建了一个全新的 C 对象,而您的模拟对象从未被使用过。 我已经稍微修改了你的方法来解决这个问题。
public static String readParams(C c, String anyString){
Map<String, String> map = c.methodCall("myString");
return "returnString";
}
当您初始化响应时,您可以更改为以下代码,传递您模拟的 c。
String response = A.readParams(c, "anyString");
我在这里更新的工作代码..
import java.util.Map;
import com.openbank.tr.util.ParamStore;
public class Instrument {
ParamStore parameterStoreMock;
public Instrument(){
parameterStoreMock = new ParamStore();
}
public static String readParams(String s, ParamStore parameterStoreMock){
Map<String, String> parameterMap = parameterStoreMock.getParams("let");
System.out.println(parameterMap);
return "string";
}
}
import java.util.HashMap;
import java.util.Map;
public class ParamStore {
public ParamStore(){
System.out.println("constructor");
}
public Map<String, String> getParams(String param){
Map<String, String> map = new HashMap<String, String>();
map.put("a", "A");
map.put("b", "B");
map.put("c", "C");
return map;
}
}
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.verify;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import com.openbank.tr.util.ParamStore;
@RunWith(MockitoJUnitRunner.class)
public class InstrumentTest {
@Mock
ParamStore parameterStore;
@Test
public void readParameterStore() throws Exception {
Map<String, String> parameterMap = new HashMap<>();
parameterMap.put("e", "EE");
parameterMap.put("f", "FF");
parameterStore = Mockito.mock(ParamStore.class);
Mockito.when(parameterStore.getParams("let")).thenReturn(parameterMap);
String response = Instrument.readParams("someString", parameterStore);
verify(parameterStore).getParams("let");
if (response != null)
assertTrue(true);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.