java – 可变输出Mockito模拟

我有一个类WidgetProcessor,它依赖于另一个类FizzChecker:

public class FizzChecker {
    public boolean hasMoreBuzz() {
        // Sometimes returns true, sometimes returns false.
    }
}

这个hasWoreBuzz()方法是从WidgetProcessor里面调用的,如下所示:

public class WidgetProcessor {
    public int process() {
        while(fizzChecker.hasMoreBuzz()) {
            // ... process stuff in here
        }
    }
}

我想在以下时间编写测试用例:

> fizzChecker.hasMoreBuzz()在第一次调用时返回false(因此循环永远不会执行)
> fizzChecker.hasMoreBuzz()在第5次调用时返回false

我正在试图弄清楚如何用Mockito来实现这一目标.到目前为止,我最好的(可怕的)尝试:

WidgetProcessor fixture = new WidgetProcessor();
FizzChecker mockFizzChecker = Mockito.mock(FizzChecker.class);

// This works great for the first test case, but what about the 2nd
// where I need it to return: true, true, true, true, false?
Mockito.when(mockFizzChecker).hasMoreBuzz().thenReturn(false);

fixture.setFizzChecker(mockFizzCheck);

fixture.process();

// Assert omitted for brevity

提前致谢.

最佳答案
您可以pass in multiple values to thenReturn, or keep chaining.对stubbed方法的连续调用将按顺序返回操作,重复所有调用的最终操作.例子:

// will return true four times, and then false for all calls afterwards
when(mockFizzChecker.hasMoreBuzz()).thenReturn(true, true, true, true, false);
when(mockFizzChecker.hasMoreBuzz())
    .thenReturn(true)
    .thenReturn(true)
    .thenReturn(true)
    .thenReturn(true)
    .thenReturn(false);
// you can also switch actions like this:
when(someOtherMock.someMethodCall())
    .thenReturn(1, 2)
    .thenThrow(new RuntimeException());

您可能希望单独设置它们:

public class WidgetProcessorTest {
  private WidgetProcessor processor;
  private FizzChecker mockFizzChecker;

  @Before public void setUp() {
    processor = new WidgetProcessor();
    mockFizzChecker = Mockito.mock(FizzChecker.class);
    processor.setFizzChecker(mockFizzChecker);
  }

  @Test public void neverHasBuzz() {
    when(mockFizzChecker.hasMoreBuzz()).thenReturn(false);
    processor.process();
    // asserts
  }

  @Test public void hasFiveBuzzes() {
    when(mockFizzChecker.hasMoreBuzz())
        .thenReturn(true, true, true, true, false);
    processor.process();
    // asserts
  }
}

最后一点:实际上,您可能会发现需要协调多个调用(例如hasMoreBuzz和getNextBuzz).如果它开始变得复杂,你预见到在很多测试中写这个,考虑跳过Mockito而不是implementing a FakeFizzChecker.

转载注明原文:java – 可变输出Mockito模拟 - 代码日志