任何人都可以解释mockito中正在进行的Stubbing 以及它如何帮助在Junit Testcase中编写并模拟这些方法。
答案 0 :(得分:4)
OngoingStubbing是一个接口,允许您指定要响应呼叫的操作。 你永远不需要直接参考OnglingStubbing;所有对它的调用应该在以when
开头的语句中作为链式方法调用发生。
// Mockito.when returns an OngoingStubbing<String>,
// because foo.bar should return String.
when(foo.bar()).thenReturn("baz");
// Methods like thenReturn and thenThrow also allow return OngoingStubbing<T>,
// so you can chain as many actions together as you'd like.
when(foo.bar()).thenReturn("baz").thenThrow(new Exception());
请注意,Mockito至少需要调用一次OngoingStubbing方法,否则会抛出UnfinishedStubbingException。但是,直到你下次与Mockito交互时才知道存根未完成,所以这可能是导致非常奇怪错误的原因。
// BAD: This will throw UnfinishedStubbingException...
when(foo.bar());
yourTest.doSomething();
// ...but the failure will come down here when you next interact with Mockito.
when(foo.quux()).thenReturn(42);
虽然在技术上可以保留对OngoingStubbing对象的引用,但Mockito没有定义该行为,并且通常被认为是一个非常糟糕的主意。这是因为Mockito是有状态的,operates via side effects during stubbing。
// BAD: You can very easily get yourself in trouble this way.
OngoingStubbing stubber = when(foo.bar());
stubber = stubber.thenReturn("baz");
stubber = stubber.thenReturn("quux");