Sei sulla pagina 1di 23

Mocks, Mockito, and Spock

­ Ravi Hasija

What are mocks?

Mocks or mock objects simulate the behavior of complex, real (non­mock) objects and are therefore useful when a real object is impractical or impossible to incorporate into a unit test.

They provide:

Default values unless stubbed

Can help verify interactions, order of interaction, method parameters etc.

Mockito???

Mockito is a Java based mocking framework that allows you to write beautiful tests with clean & simple API.

Tests are very readable and they produce clean verification errors.

It is NOT an expect­run­verify library like EasyMock or jMock i.e. you ask questions about interactions after execution of business method.

How to Mock in Mockito

@Mock BookDao mockedBookDao

BookDao mockedBookDao = mock(BookDao.class);

This will mock all methods in BookDao class and provide default values.

Initialize annotated mocks

Annotate Junit Test class with:

@RunWith(MockitoJUnitRunner.class)

OR

Add line below to setup method:

MockitoAnnotations.initMocks(this);

Stubbing

Stubbing is adding canned response to Mock object methods.

Examples:

1) when(list.get(0)).thenReturn('Hello'); 2) when(mockedMap.get(”key”).thenReturn(”someValue”); 3) doThrow(new IllegalStateException(”Illegal”).when(dao).get(1L);

Verify behavior

”Verify” helps verify that certain methods were called ”n” times or were never called.

Example:

1) Default is 1.

2) times(n)

Verify behavior (cont'd)

1) atLeastOnce()

2) atLeast(n)

3) atMost(n))

4) verifyZeroInteractions(mock1, mock2,

);

Verify behavior (cont'd)

verifyZeroInteractions(mockTwo, mockThree);

Verify (inOrder) – OrderProcessServiceTest

Can be used to make sure certain business steps occur in order.

Don't have to verify all interactions

You can create InOrder object passing only mocks that are relevant for in­order verification.

Stubbing (cont'd)

Stubbing consecutive calls – same mock method can be stubbed multiple times.

show_Multiple_Stubbing_1()

show_Multiple_Stubbing_2()

last_Stubbing_Rules()

Stubbing Exceptions

Stubbing exceptions:

when(mockedDao.get(1).thenThrow(new

RunTimeException());

doThrow(new IllegalStateException(”Illegal”).when(mockDao).remove

(1);

Spy'ing

(007)

Spy are partial mocks.

Spy:

Calls real methods unless the method is stubbed.

Should be used sparingly.

Use of too much spy is potential code smell.

Ex: ProfileServiceTest.demoSpy()

Argument Captor

Mockito verifies argument values in natural java style: by using an equals() method. In some situations though, it is helpful to assert on certain arguments after the actual verification.

For example:

ArgumentCaptorDemoTest.demo_Argument_Captor.

Descriptive error messages

Let's cause a validation error: let's change a cardinality

Features:

Spock

Groovy based

No assertion API

Extensible: already integrates with Guice, Spring, Unitils

Detailed information

Spock Terminology

Fixture methods:

def setup() {}

def cleanup() {}

def setupSpec() {}

def cleanupSpec() {}

Spock Terminology (cont'd)

Feature methods:

def "pushing an element on the stack"() { // blocks go here

}

Spock Terminology (cont'd)

Blocks:

1. setup:

2. when:

3. then:

4. expect:

5. cleanup:

6. where:

Demo the methods

PromotionServiceSpec

OrderProcessServiceSpec

StepwiseDemo

Mockito Project info

GitHub repository:

git://github.com/RaviH/MockitoDemo1.git

mkdir demo; cd demo; git clone git://github.com/RaviH/MockitoDemo1.git cd MockitoDemo1; mvn install; mvn idea:idea;

Use IntelliJ to open it.

Spock Project info

GitHub repository:

git://github.com/RaviH/SpockDemo.git

mkdir demo; cd demo; git clone git://github.com/RaviH/SpockDemo.git

cd SpockDemo; mvn install; mvn idea:idea

Use IntelliJ to open it.

References

http://www.rapaul.com/2010/06/10/avoiding­

brittle­tests­with­mockitos­argument­captor/

http://gojko.net/2009/10/23/mockito­in­six­easy­

examples/

http://code.google.com/p/spock/

Thank You

Let's

mock

PLEASE!!!

:D