谁能解释一下 是什么?正在进行的 stub 在 mockito 中以及它如何帮助在 Junit Testcase 中编写和模拟方法。
最佳答案
OngoingStubbing是一个接口(interface),允许您指定响应方法调用而采取的操作。您永远不需要直接引用 OngoingStubbing;所有对它的调用都应该在以 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 交互时,它才知道 stub 未完成,因此这可能是非常奇怪的错误的原因。
// 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");
关于junit - mockito 中的持续 stub 是什么以及我们在哪里使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29281061/