What is ongoingstubbing in mockito and where we use it?

Gowtham Murugesan picture Gowtham Murugesan · Mar 26, 2015 · Viewed 11k times · Source

Can any one explain what is ongoing Stubbing in mockito and how it helps writing in Junit Testcase and mocking the methods.

Answer

Jeff Bowman picture Jeff Bowman · Mar 26, 2015

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");