我正在使用 Mockito 和 Junit 版本:4.8.2
我无法模拟需要任何接口(interface)对象的方法。
例如,
public interface If extends Xyz {
}
Class Abc {
protected List <String> getIPAddress(If x, String n) {
}
}
这是示例测试方法:
@Test
public void testGetIPAddress() {
Abc mockAbc = mock(Abc.class, CALLS_REAL_METHODS);
when(mockAbc.getIPAddress(any(Xyz.class), anyString())).thenReturn(new List <String>());
}
当我运行上述方法时,我得到:
NullPointerException
更新
实际上我发现问题出在实例化模拟对象时使用“CALLS_REAL_METHODS”
。即使我使用
when(mockAbc.getIPAddress(any(If.class), anyString())).thenReturn(null);
它正在抛出 NPE。原因可能是它仍在调用真正的方法。 在这种情况下如何覆盖调用真正的方法?
最佳答案
您需要调用getIpAdress
与 If
不是Xyz
此外,new List <String>()
不起作用,如 List
是一个接口(interface),使用new ArrayList<String>()
相反:
@Test
public void testGetIPAddress() {
Abc mockAbc = mock(Abc.class, CALLS_REAL_METHODS);
when(mockAbc.getIPAddress(any(If.class), anyString())).thenReturn(new ArrayList<String>());
}
关于java - 无法模拟需要接口(interface)对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33079044/