简体   繁体   English

使用Mockito模拟接口时发生异常

[英]Exception when mocking Interface with Mockito

I am trying to test that an Interface method was called with and exact value passed in. I'm getting the following error: 我正在尝试测试调用了Interface方法并传递了确切的值。我收到以下错误:

org.mockito.exceptions.misusing.UnfinishedVerificationException: Missing method call for verify(mock) here: -> at com.example.app.initialize(example.java:136) org.mockito.exceptions.misusing.UnfinishedVerificationException:在此处缺少对verify(mock)的方法调用:-> com.example.app.initialize(example.java:136)

Example of correct verification: verify(mock).doSomething() 正确验证的示例:verify(mock).doSomething()

The error is being thrown on this verification line: 在此验证行上引发了错误:

Mockito.verify(callback).onInitializeResult("initialized");

My Interface class: 我的界面类:

public interface InitCallback {
/**
 * Returns whether or not the app was initialized.     .
 */
    void onInitializeResult(String result);
}

My Unit Test: 我的单元测试:

@Test
    public void initializationTest(){
        InitCallback callback = Mockito.spy(new InitCallback() {
            @Override
            public void onInitializeResult(String result) {

            }
        });
        mExample.initialize(mContext, callback);
        Mockito.verify(callback).onInitializeResult("initialized");
    }

I also tried to replace the callback mock with: 我还尝试将回调模拟替换为:

InitCallback callback = Mockito.mock(InitCallback.class);
Mockito.doNothing().when(callback).onInitializeResult(Mockito.anyString());

However I still get the same error. 但是我仍然收到相同的错误。 The interface only has 1 method and it is not final. 该接口只有一种方法,并且不是最终方法。 Any Thoughts? 有什么想法吗?

It turns out that mExample was calling another mocked instance whose methods were not defined. 事实证明,mExample正在调用另一个未定义方法的模拟实例。 From another Stack Overflow post Link 从另一个堆栈溢出发布链接

Mockito throws exceptions if you misuse it so that you know if your tests are written correctly. 如果您滥用Mockito,它将抛出异常,以便您知道测试是否正确编写。 The gotcha is that Mockito does the validation next time you use the framework (eg next time you verify, stub, call mock etc.) . 问题在于,Mockito在您下次使用框架时进行验证(例如,下次验证,存根,调用模拟等) But even though the exception might be thrown in the next test, the exception message contains a navigable stack trace element with location of the defect. 但是,即使在下一个测试中可能抛出异常,该异常消息仍包含具有缺陷位置的可导航堆栈跟踪元素。 Hence you can click and find the place where Mockito was misused. 因此,您可以单击并找到滥用Mockito的地方。

So in the case posted in the question, The exception was generated in 因此,在问题中发布的案例中,异常是在

mExample.initialize(mContext, callback);

but not thrown until the next time verify was called. 但直到下一次调用verify时才抛出。

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

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