【问题标题】:How to prevent a method from calling another method in test?如何防止一个方法在测试中调用另一个方法?
【发布时间】:2023-04-01 19:58:01
【问题描述】:
public void makeLoginRequest(){
    view.log(sessionHandler.getEncodedCredentials());
    Call loginCall = apiService.getLoginInfo("application/json", "application/json"
            , "SPT", "Android", sessionHandler.getEncodedCredentials());

   loginCall.enqueue(new Callback<User>() {
        @Override
        public void onResponse(Call<User> call, Response<User> response) {
            handleLoginResponse(response);
        }

        @Override
        public void onFailure(Call<User> call, Throwable t) {
            handleLoginFailure(t);
        }
    });
}

我正在尝试使用 JUnit 和 Mockito 测试此方法。此方法属于演示者类。为了测试这个我跑 presenter.makeLoginRequest(); 那么当 onResponse 被调用时 我使用永远不会被调用的verify(presenter).handleLoginResponse(response);。问题是它将继续运行handleLoginResponse(response); 中的所有内容。我不想执行这个方法中的什么,而只需要验证这个方法是否被调用。 如何忽略方法执行,或者测试它的最佳方法是什么?

【问题讨论】:

    标签: java android junit mockito robolectric


    【解决方案1】:

    有两种方法:

    1. 让您的演示者成为mock 对象
    presenter = mock<Presenter>()
    
    1. 将此添加到您的测试中
    doNothing().when(presenter).handleLoginResponse(any()); 
    

    【讨论】:

    • 感谢您的回答。我嘲笑了演示者类,但这会导致handleLoginResponse(response) 不被调用。当我监视演示者类时它会起作用,尽管 doNothing 被忽略并且该方法仍然被执行:(
    • 整个目的不就是测试不调用handleLoginResponse吗?即使你模拟了presenter类,verify(presenter).handleLoginResponse(response);仍然可以验证
    • 其实可以的!我只是忘了在验证中添加any()。谢谢巴赫! :)
    • 很高兴它有帮助:)
    猜你喜欢
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 2015-12-15
    • 1970-01-01
    • 2015-06-16
    相关资源
    最近更新 更多