【发布时间】:2013-11-26 15:14:40
【问题描述】:
查看下面的代码,我只希望对getSand() 的调用会发生一次,但测试失败了,对它进行了四次调用。这些电话发生在哪里?我想编写一个测试来确保只调用一次getSand()。
来源
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class DeepSandTest {
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
SandBox mockSandBox;
@Test
public void should(){
when(mockSandBox.getSand().doA()).thenReturn(1);
when(mockSandBox.getSand().doB()).thenReturn(1);
when(mockSandBox.getSand().doC()).thenReturn(1);
DeepSand deepSand = new DeepSand(mockSandBox);
deepSand.getTipple();
verify(mockSandBox, times(1)).getSand();
}
public class DeepSand{
private SandBox sandBox;
public DeepSand(SandBox sandBox) {
this.sandBox = sandBox;
}
public void getTipple(){
Sand sand = sandBox.getSand();
sand.doA();
sand.doB();
sand.doC();
}
}
public interface SandBox{
public Sand getSand();
}
public interface Sand{
public Integer doA();
public Integer doB();
public Integer doC();
}
}
输出
org.mockito.exceptions.verification.TooManyActualInvocations:
mockSandBox.getSand();
Wanted 1 time:
-> at DeepSandTest.should(DeepSandTest.java:26)
But was 4 times. Undesired invocation:
-> at DeepSandTest.should(DeepSandTest.java:20)
详细信息 Java 1.6、JUnit 4.11、Mockito 1.9.5
经验教训
如果您将深度存根视为模拟对象的树,那么您应该只验证叶子(“链中的最后一个模拟”),因为节点包含在设置叶子行为所需的调用链中。换句话说,节点在叶子的设置过程中被调用。
【问题讨论】: