Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is ongoingstubbing in mockito and where we use it?

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

like image 910
Gowtham Murugesan Avatar asked Mar 26 '15 14:03

Gowtham Murugesan


People also ask

What is OngoingStubbing in Mockito?

public interface OngoingStubbing<T> Simply put: "When the x method is called then return y".

What is the difference between doReturn and thenReturn?

* 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.

What is the use of when thenReturn in Mockito?

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

How do Mockito mocks work?

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.


1 Answers

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");
like image 160
Jeff Bowman Avatar answered Sep 20 '22 19:09

Jeff Bowman