【问题标题】:Application hangs on mocked method call应用程序挂起模拟方法调用
【发布时间】:2016-06-27 18:26:37
【问题描述】:

我正在尝试模拟我的 AuthenticationManager 课程。我这样做如下:

AuthenticationManager authManager = Mockito.mock(AuthenticationManager.class);

我只想模拟它的一种方法,PerformSignInAsync。此方法返回void。传递给此方法的参数之一是处理程序,它需要调用其onComplete 事件。我正在尝试使用ArgumentCaptor 这样做:

ArgumentCaptor<AuthenticationResponseHandler> authResponseCaptor = ArgumentCaptor.forClass(AuthenticationResponseHandler.class);

以下是我如何模拟我想要模拟的方法。当测试到达真正的方法时,我已经使用调试器逐步完成并且它正在被 Mockito 调用。所以我认为问题一定是我触发了onComplete 调用。 一旦真正的 PerformSignInAsync 被调用,应用程序就会挂起,不会引发任何异常。

doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) {
            Object[] args = invocation.getArguments();
            AuthenticationResponseHandler handler = (AuthenticationResponseHandler) args[4];
            // The line below is what I want triggered
            handler.onComplete(AuthenticationOperation.SignIn, responseToReturn);
            return null;
        }
    }).when(authManager).PerformSignInAsync(
            anyString(),
            anyString(),
            anyBoolean(),
            Matchers.any(UserLOBSystemType.class),
            authResponseCaptor.capture(),
            anyString(),
            anyString());

我也试过用下面的代码触发onComplete,但无济于事:

    authResponseCaptor.capture().onComplete(AuthenticationOperation.SignIn, responseToReturn);

【问题讨论】:

  • 你的处理程序呢,它也是模拟的吗?你能提供一个线程转储吗?

标签: java android unit-testing mockito void


【解决方案1】:

问题原来是我在问题的代码块中引用了 authManager 的另一个实例,而不是实际方法中使用的实例。结果,模拟没有被触发。

【讨论】:

    猜你喜欢
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    相关资源
    最近更新 更多