Mockito:多次调用同一方法 [英] Mockito: multiple calls to the same method

查看:512
本文介绍了Mockito:多次调用同一方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Mockito嘲笑一个对象,对该对象的相同方法被多次调用,并且我想每次都返回相同的值.
这就是我所拥有的:

I am mocking an object with Mockito, the same method on this object is called multiple times and I want to return the same value every time.
This is what I have:

LogEntry entry = null; // this is a field
// This method is called once only.
when(mockLogger.createNewLogEntry()).thenAnswer(new Answer<LogEntry>() {
  @Override
  public LogEntry answer(InvocationOnMock invocationOnMock) throws Throwable {
    entry = new LogEntry();
    return entry;
  }
});
// This method can be called multiple times, 
// If called after createNewLogEntry() - should return initialized entry.
// If called before createNewLogEntry() - should return null.
when(mockLogger.getLogEntry()).thenAnswer(new Answer<LogEntry>() {
  @Override
  public LogEntry answer(InvocationOnMock invocationOnMock) throws Throwable {
    return entry;
  }
});

问题是,似乎我的getLogEntry方法仅被调用了一次.对于所有后续调用,将返回null,而我在测试中得到了NPE.
我该如何告诉Mockito对所有呼叫使用存根版本?

The problem is, it seems that my getLogEntry method is called only once. For all subsequent invocations, null is returned instead and I get NPEs in tests.
How can I tell mockito to use stubbed version for all calls?

================================================ ==================
后代验尸

=================================================================
Post mortem for future generations

我做了一些额外的调查,和往常一样,这不是库的错,这是我的错.在我的代码中,调用createNewLogEntry()之前称为getLogEntry()的方法之一. NPE是绝对合法的,该测试实际上在我的代码中发现了一个错误,而不是我在Mockito中发现了一个错误.

I did some additional investigation and as always it is not library's fault, it is my fault. In my code one of the methods called getLogEntry() before calling createNewLogEntry(). NPE was absolutely legitimate, the test actually found a bug in my code, not me finding bug in Mockito.

推荐答案

您的存根应该可以按需工作.来自 Mockito文档:

Your stub should work as you want it. From Mockito doc:

一旦存根,该方法将始终返回存根值,无论 被调用多少次.

Once stubbed, the method will always return stubbed value regardless of how many times it is called.

这篇关于Mockito:多次调用同一方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆