【问题标题】:Mockito error : "Wanted but not invoked:.. However, there were other interactions with this mock"Mockito 错误:“需要但未调用:.. 但是,此模拟还有其他交互”
【发布时间】:2013-08-15 13:16:01
【问题描述】:

当我尝试通过传递强制转换的值来模拟重载方法时,出现以下错误。

例如为了模拟 ABCClass.logWarn(Logger log,String , String description, Throwable e);

我在做

`ABCClass.logWarn(null,WarningString, description, (Throwable)null); 
...\\ The rest of the methods are standard...
verify(event).setStatus((Throwable)null);//**Line 76**

但是当我运行我的测试用例时,我得到了以下错误

  ABCClassTest.testLogWarn:76 
    Wanted but not invoked:
    MockEvent.setStatus(null);
    -> at com.path.ABCClassTest.testLogWarn(ABCClassTest.java:76)

However, there were other interactions with this mock:.....

为什么 setStatus(null) 会被调用,即使在专门调用了 setStatus((Throwable)null);?

其他细节

logWarn的定义

private static void logWarn(String eventType, String eventName, String errMsg, Throwable e) {

        AnEvent event = AnEventFactory.create(eventType);
        event.setName(eventName);
        if(e!=null)
            event.setStatus(e);//so this is never called if the throwable is null.
    //How do I modify the verify behavior?
        /*
                   Bleh */


        event.completed();
    }

【问题讨论】:

    标签: java unit-testing testing mockito powermock


    【解决方案1】:

    强制转换不会改变变量引用的对象。当您以与其类型不匹配的方式使用变量时,它只会使编译器不会抱怨。所以你真的在verify之后将null传递给setStatus

    当然,如果您要问为什么您正在测试的代码实际上并未调用 setStatus,您需要先发布它,然后才能有人告诉您。

    【讨论】:

    • 我认为你的回答很有道理。我添加了关于 logWarn 方法的代码,如果传递的参数为 Null,则实际上不会调用 setStatus
    • @DavidWallace.Ive 为问题添加了更多细节。有什么想法吗?
    • 所以我不明白你的问题。当e 为空时,您的代码显然不会调用setStatus。你有一个verify 断言它确实被调用了;当然,verify 失败了。你觉得哪里不正常?
    • 抱歉打扰了。我在这里找到了我想要的东西。 stackoverflow.com/questions/12862659/…
    • 好的,你的问题从来没有说你想要验证你的方法没有被调用。我已投票以“不清楚”结束您的问题 - 任何有您确切问题的人可能最好不要找到这个问题。
    【解决方案2】:

    作为 Mockito 的新手,我并没有完全意识到自己在寻找什么。但this 正是我想要的。 希望这可以帮助其他遇到类似问题的人。

    【讨论】:

      猜你喜欢
      • 2011-12-18
      • 2011-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多