简体   繁体   English

无法模拟需要接口对象的方法

[英]Not able to mock method which expects interface object

I'm using Mockito with Junit version : 4.8.2 我在Junit版本中使用Mockito: 4.8.2
I'm not able to mock methods which expects any interface objects. 我无法模拟需要任何接口对象的方法。

For example, 例如,

public interface If extends Xyz {
}

Class Abc {
    protected List <String> getIPAddress(If x, String n) {
    }
}

This is sample test method: 这是样本测试方法:

@Test
public void testGetIPAddress() {
    Abc mockAbc = mock(Abc.class, CALLS_REAL_METHODS);
    when(mockAbc.getIPAddress(any(Xyz.class), anyString())).thenReturn(new List <String>());
}

When I run the above method, I get: NullPointerException 当我运行上述方法时,我得到: NullPointerException

UPDATES 更新

Actually I found out that the problem is using "CALLS_REAL_METHODS" , when instantiating mocked object. 实际上,我发现在实例化"CALLS_REAL_METHODS"对象时问题出在使用"CALLS_REAL_METHODS" Even if I use 即使我用

when(mockAbc.getIPAddress(any(If.class), anyString())).thenReturn(null);

It is throwing NPE. 它正在抛出NPE。 The reason might be it's still calling the real method. 原因可能是它仍在调用real方法。 How do I override calling the real method in this case? 在这种情况下,如何覆盖调用real方法?

you need to call getIpAdress with an If not an Xyz 你需要调用getIpAdressIf不是Xyz

Also, new List <String>() won't work, as List is an interface, use new ArrayList<String>() instead: 另外, new List <String>()将不起作用,因为List是一个接口,请改用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>());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM