【问题标题】:Mocking/Replacing interface method inside another method在另一个方法中模拟/替换接口方法
【发布时间】:2016-02-22 00:10:05
【问题描述】:

我有声明方法的接口

public interface EventAdder{
void addEvent(Event e);
}

现在我有了一个使用这个接口的类。

public class Container{

//some code here

private EventAdder ea; 

public void checkPainterState(){

//some code which I want to test inside checkPainterState

ea.addEvent(new Event(val1, val2));

}
}

我正在使用创建Container object 的外部测试类。 我想测试方法checkPainterState() 而不在测试中的checkPainterState() 方法中调用ea.addEvent()。我如何在测试中模拟/监视/替换此ea objectea.AddEvent 方法以防止使用?

【问题讨论】:

  • 不清楚。您想准确测试什么?那个.addEvent() 叫什么?另外,不相关:为什么ea public 在你的Container 中?
  • 我修复了代码,因为它与这些名称有点混淆。是的,ea。应该是私人的 我在写这个问题时犯了一个小错误。我想测试checkPainterState()

标签: java unit-testing testing junit mockito


【解决方案1】:

因为你使用mockito,所以声明就这么简单:

final EventAdder adder = mock(EventAdder.class);

// make it the adder for your container, run the method, then

verify(adder).addEvent(any(Event.class)); // or other argument matcher

当你用 Mockito 模拟 void 方法时,它的默认行为就是什么都不做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多