查看下面的代码,我只希望调用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
得到教训
如果您将深度存根视为模拟对象的树,那么您应该只验证叶子(“链中的最后一个模拟”),因为节点包含在设置叶子行为所需的调用链中。换一种说法,在叶子的设置过程中调用节点。