Skip to content


May 28, 2010

//given //when //then

// when thenReturn clauses provide “Data or functional behavior” to the classes.
These classes can be simple POJO’s or services as well.

//Verify checks if the calls took place in the sequence expected – specifically checking of call stack of the mocked class.

So we have, service being told what to return when called , then controller called
then verify if service was called when controller fn called?. By breaking the test into given, when & then, future maintainers of the tests will more quickly understand which parts of the test relate to setup, exercising the SUT and asserting. Use the BDDMockito 1.8 classes for given clause instead of when clause used in Mockito class. Simple example of using mockito for a quick understanding is below:
Competency – pojo, CompetencyManager – my controller, CompetencyService – @Mock class.

	public void testProcessComp() {
 		Competency c = new Competency("java");
                            //Create DATA here...
          //Make the call  - realistic	

             //check if Service was called  in the stack above.

1. It’s not just call stack trace verification but also – direct method verification.
call the method and verify if it – itself was called.

2. Stubbing is the adding of method definition with custom data expected. when/thenReturn add this

behavior to the mock object.

3. hamcrest is used for matching – use assertThat is this – matchers – similar to assert keyword. it can be

used along.

4. Verifying count of invocations in the stack trace. Either you use the mock(a.class) or you do @Mock
along with usage of of @RunWith. (Omitting either one would result in null object usage during the test!)

public class MockList {
	List arl;
	public void setup()
	   //arl = mock(List.class);
	public   void testList()
		verify(arl, times(4)).add("four");

5.doThrow|doAnswer – used for stubbing the return of an exception from a method. Specifically for void return methods.

6. consecutive stubbing : Sequence of calls and returns recorded for same method:
when(mock.someMethod(“some arg”)) .thenReturn(“one”, “two”, “three”);
when(mock.someMethod(“some arg”)) .thenThrow(new RuntimeException()) .thenReturn(“foo”);

7. Use Answer interface to use the args in output return stubbing.

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: