有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法模拟驻留在不同项目中的类的对象

这就是我模拟另一个项目中存在的类Client的对象的方式:

@Mock
private Client client;

//Mocking method of class client - 

@Test
public void test()
{
    Mockito.when(client.getPassportDetail(Matchers.eq(bytes),Matchers.eq(properties)))
           .thenReturn(hash);
}

类客户端的结构:

class Client
{

    public static boolean loadLibraries(Properties properties) {
    }

    public HashMap<String, String> getPassportDetail(byte[] b, Properties properties) throws Exception{
        if (!loadLibraries(properties)) 
        {
            throw new UnsatisfiedLinkError();
        }
    }

因此,当我模拟getPassportDetail方法时,会调用它,而不是模拟


共 (1) 个答案

  1. # 1 楼答案

    这是一个常见的错误。实际上,@Mock注解需要更多的东西来工作

    您有3种选择:

    @RunWith(MockitoJUnitRunner.class) 
    

    去你的测试班

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
    }
    

    还有第三种选择,在下面的评论中建议:

    There's a third option, which is better than either of these two. Use the new Mockito Rule - @Rule public MockitoRule rule = MockitoJUnit.rule();. More detail at my answer here, which also explains why this is the best of the three options.

    就这些了

    您可以随时参考http://www.baeldung.com/mockito-annotations了解更多信息和详细解释