Can any one explain what is ongoing Stubbing in mockito and how it helps writing in Junit Testcase and mocking the methods.
public interface OngoingStubbing<T> Simply put: "When the x method is called then return y".
* Type safety : doReturn takes Object parameter, unlike thenReturn . Hence there is no type check in doReturn at compile time. In the case of thenReturn , whenever the type mismatches during runtime, the WrongTypeOfReturnValue exception is raised.
The thenReturn() methods lets you define the return value when a particular method of the mocked object is been called. The below snippet shows how we use thenReturn to check for multiple values. Iterator i = mock(Iterator. class );
With Mockito, you create a mock, tell Mockito what to do when specific methods are called on it, and then use the mock instance in your test instead of the real thing. After the test, you can query the mock to see what specific methods were called or check the side effects in the form of changed state.
OngoingStubbing is an interface that allows you to specify an action to take in response to a method call. You should never need to refer to OngoingStubbing directly; all calls to it should happen as chained method calls in the statement starting with 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());
Note that Mockito requires at least one call to an OngoingStubbing method, or else it will throw UnfinishedStubbingException. However, it doesn't know the stubbing is unfinished until the next time you interact with Mockito, so this can be the cause of very strange errors.
// 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);
Though it is technically possible to keep around a reference to an OngoingStubbing object, that behavior is not defined by Mockito, and is generally considered a very bad idea. This is because Mockito is stateful, and 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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With