Posts Tagged ‘refcard’

Mockito uses a lazy approach for stubbing and when a not stubbed method is called it returns a default value instead of throwing an exception (like EasyMock). This is very useful to not overspecify the test.

A default returned value depends on a return type of a stubbed method. For methods eturning collections we have an empty collection, for numbers – 0, for booleans false, for ordinary objects – null (in Mockito 2.0 the set of not null values will be extended – this can be also achieved with 1.9.x and ReturnsMoreEmptyValues answer).

Mockito logo

Before we go any further a quick introduction do Answers (you can skip to the next paragraph if Answers are for you like an open book). In addition to simple stubbing based on desired value passed to Mockito directly:

given(tacticalStationMock.getNumberOfTubes())
    .willReturn(TEST_NUMBER_OF_TORPEDO_TUBES);

or for consecutive calls:

given(tacticalStationMock.getNumberOfEnemyShipsInRange()).willReturn(2, 3);

the stubbing API provides a way to pass an object with the logic to determine what should be returned in given case (based on method arguments or even an internal state (for consecutive calls)). A simple practical example returning always the first parameter passed to the called method:

public class ReturnFirstArgumentAnswer implements Answer<Object> {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        Object[] arguments = invocation.getArguments();
        if (arguments.length == 0) {
            throw new MockitoException("...");
        }
        return arguments[0];
    }
}

A sample usage when stubbing:

given(mock.methodToStub("arg1", "arg2"))
    .willReturn(new ReturnFirstArgumentAnswer());

Mockito provides a set of build-in answers. Some of them (like ThrowsException or CallRealMethods) are used by Mockito internally, but some others (like ReturnsArgumentAt introduced in 1.9.5) can be also useful for developers writing tests.

Let’s return to the main topic. Sometimes it is useful to change those default values. In addition to using the answer mechanism for stubbing a specific method calls Mockito provides a way to specify an answer which will be used for every not stubbed method execution on given mock. To do so we can use a static mock() method which in addition to a class to mock takes an additional parameter – a default answer.

mock(SpaceShip.class, Mockito.RETURNS_DEFAULTS);

As returns defaults is a default behavior in Mockito above code is just a more explicit version of:

mock(SpaceShip.class);

but we can use this construction to achieve a few interesting behaviors. One of the predefined answers provided by Mockito is RETURNS_DEEP_STUBS. It causes an automatic stubbing of chained methods calls and allows to do following:

SpaceShip spaceShipMock = mock(SpaceShip.class, Mockito.RETURNS_DEEP_STUBS);
given(spaceShipMock.getTacticalStation().getNumberOfTubes()).willReturn(5);

Please note that with default configuration it would cause NullPointerException due to the fact spaceShipMock.getTacticalStation() returns null. With RETURNS_DEEP_STUBS Mockito under the hood creates a mock for every middle method call. This is an equivalent of:

//NOTE. Deep stubs implemented manually - no more needed with RETURNS_DEEP_STUBS.
//See the previous example with an equivalent functionality in 2 lines.
SpaceShip spaceShipMock = mock(SpaceShip.class);
TacticalStation tacticalStationMock = mock(TacticalStation.class);
given(spaceShipMock.getTacticalStation()).willReturn(tacticalStationMock);
given(tacticalStationMock.getNumberOfTubes()).willReturn(5);

As a bonus, deep stubbing allows to perform a verification (only) on the last mock in the chain:

verify(spaceShipMock.getTacticalStation()).getNumberOfTubes();

Another provided answer is RETURNS_MOCKS. This tries to return default value using ReturnsMoreEmptyValues answer (an extended version of a default ReturnsEmptyValues), but if it fails a mock is returned. Only in the situation where the return type cannot be mocked (e.g. is final) null is returned.

mock(OperationsStation.class, Mockito.RETURNS_MOCKS);

Sometimes it can be useful to stub specified methods, but delegate remaining calls to the real implementations. It can be done with CALLS_REAL_METHODS. It can be useful for example when testing an abstract class (just the implemented methods without the need to subclass to create a concrete subclass).

mock(AbstractClass.class, Mockito.CALLS_REAL_METHODS);

Please note that using RETURN_DEEP_STUBS, RETURN_MOCKS and CALLS_REAL_METHODS should be not needed when dealing with well crafted code, written with the usage of Test-Driven Development. Nevertheless sometimes it is required to write tests for legacy code before a try to refactor it.

From a set of default answers defined in Mockito.java, there is also a very useful RETURNS_SMART_NULLS option. This returns SmartNull class instance instead of plain null, which provides a hint which mock stubbing was not performed correctly (and caused NPE). I wrote more about this mode some time ago in Beyond the Mockito Refcard #1.

In addition to define a default answer we can use any class which implements org.mockito.stubbing.Answer interface – both provided by Mockito or hand written. One more tip. In case you would like to use RETURNS_SMART_NULLS or ReturnsMoreEmptyValues globally for all mocks in your application you can check a trick with MockitoConfiguration.

Btw, in case you are starting an adventure with Mockito or want to learn more or just want to organize your knowledge you can be interested in my Mockito Refcard available for free from dzone.com.

Btw2, in addition if you are new to Mockito and live near Warszawa you can consider an attendance in my lecture/workshop about Mockito at Jinkubator – 18 II 2014 (next Tuesday).

Jinkubator

This post is the fourth part of the series Beyond the Mockito refcard extending released some time ago my Mockito reference card.

Advertisements

Mockito team provides two jars: mockito-core.jar and mockito-all.jar. Which is better to choose for Maven or Gradle-based project? Both of them can be downloaded manually from a project webpage and also are available in Maven Central Repository. In many Maven projects I have found that mockito-all.jar was used which isn’t the best option and I will shortly explain why.

mockito-all.jar besides Mockito itself contains also (as of 1.9.5) two dependencies: Hamcrest and Objenesis (let’s omit repackaged ASM and CGLIB for a moment). The reason was to have everything what is needed inside an one JAR to just put it on a classpath. It can look strange, but please remember than Mockito development started in times when pure Ant (without dependency management) was the most popular build system for Java projects and the all external JARs required by a project (i.e. our project’s dependencies and their dependencies) had to be downloaded manually and specified in a build script.

On the other hand mockito-core.jar is just Mockito classes (also with repackaged ASM and CGLIB). When using it with Maven or Gradle required dependencies (Hamcrest and Objenesis) are managed by those tools (downloaded automatically and put on a test classpath). It allows to override used versions (for example if our projects uses never, but backward compatible version), but what is more important those dependencies are not hidden inside mockito-all.jar what allows to detected possible version incompatibility with dependency analyze tools. This is much better solution when dependency managed tool is used in a project.

I asked to forget about ASM and CGLIB for a while. It is time to explain why. As classes from those projects are repackaged inside a Mockito JAR (i.e. put into different packages than the original ones) and they are treated by a class loader just as different classes. This means that from a dependency management point of view they are just another Mockito internal classes. The Mockito developers explain it as a way to avoid some not fixed problems with CGLIB and a class loader met in the early development phase.

This post is the third part of the series Beyond the Mockito refcard extending recently released my Mockito reference card.

Unit tests are very handy. They run fast and it is possible to execute hundreds or even thousands of them very often during development (especially useful when using TDD). Nevertheless from time to time we want to test the correctness of a part of an IoC container configuration and check how those components works together when managed by an IoC context. In this tutorial I will show how to do it in a convenient way.

The easiest solution could be to set up the whole “production” IoC context. Unfortunately depending on the size of a project it can take some time (long minutes) and in addition that configuration is likely to connect to external resources like a database or a message queue which makes restriction where those tests will be able to run. What can we do to fix it?

Very often to test interactions between selected components it is not needed to make the full featured integration tests. We can use two useful techniques together: limiting context scope (?) and mocking. The idea is to set up only needed components. This can be achieved by separate a minimal Spring configuration file using in tests (possible reusing some of existing production files). However very often there is a problem with direct dependencies which behaviors (?) are not needed in our tests, but are required to set up our beans. Doesn’t it look familiar to the situation meet also in unit tests? Mocks (and Mockito) to the rescue.

Our mocks have to be put into Spring context to be able to inject into other beans created by Spring. While it can be done using pure Spring mechanisms, there is a library which makes it much easier – Springockito written by Jakub Janczak.

Note. Pure unit tests are generally much better choice. Tests using IoC context should be only used when we really need to test behaviors within a context.

To start working with Springockito it is required to add its JAR to the project dependencies. Using Maven it could be:

<dependency>
    <groupId>org.kubek2k</groupId>
    <artifactId>springockito</artifactId>
    <version>1.0.4</version>
    <scope>test</scope>
</dependency>

With Gradle:

testCompile "org.kubek2k:springockito:1.0.4"

(change 1.0.4 to the latest released version of Springockito)

Note. The following examples are simplified to does not introduce unneeded distractions. They do not have a context configuration which is worth to test and it would be easier to use pure unit tests (without a Spring context).

Let’s take following configuration where plantWaterer object requires waterSource and waterScheduler beans:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="plantWaterer" class="info.solidsoft.refcard.mockito.PlantWaterer">
        <constructor-arg name="waterSource" ref="waterSource"/>
        <constructor-arg name="waterScheduler" ref="waterScheduler"/>
    </bean>

    <bean id="waterSource" class="info.solidsoft.refcard.mockito.RiverWaterSource">
        <constructor-arg ref="smallRiver"/>
    </bean>

    <bean id="waterScheduler" class="info.solidsoft.refcard.mockito.WaterScheduler"/>

</beans>

RiverWaterSource relies on an external resource which could be problematic during tests. To override it following configuration (with the additional namespace mockito) could be used.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mockito="http://www.mockito.org/spring/mockito"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.mockito.org/spring/mockito https://bitbucket.org/kubek2k/springockito/raw/tip/springockito/src/main/resources/spring/mockito.xsd">

    <mockito:mock id="waterSource" class="info.solidsoft.refcard.mockito.WaterSource"/>

</beans>

Make a note that there is even no try to create the original bean. This is very useful in a situation where for example DAO would like to make a connection to a database during start up (which could take some time and is very fragile).

With Springockito it is also very easy to make a spy of existing Spring bean and inject it into another bean instead of the original bean for example to verify made interactions.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mockito="http://www.mockito.org/spring/mockito"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.mockito.org/spring/mockito https://bitbucket.org/kubek2k/springockito/raw/tip/springockito/src/main/resources/spring/mockito.xsd">

    <mockito:spy beanName="waterSource"/>

</beans>

Mocks and spies created with a help of Springockito are just like “normal” mocks/spies which can be stubbed and verified. However there are two important differences. The instance of a mock/spy is created by Spring when a context is set up (in opposite to manual call Mockito.mock/spy() or using @Mock/@Spy annotation), so the easiest way to obtain it is to make an injection into our tests class (by name or by type).

@ContextConfiguration({<<configuration-files>>})
public class MockInjectionSpringockitoTest extends AbstractTestNGSpringContextTests {

    @Autowired
    private PlantWaterer plantWaterer;

    @Autowired	//it is safe - Springockito hid the original WaterSource bean
    private WaterSource waterSourceSpy;

    @Test
    public void shouldSpyInjectedObject() {
        //given - mocks/spies are already created, can be stubbed here

        //when
        plantWaterer.waterPlants();

        //then
        verify(waterSourceSpy).startWaterFlow();
    }
}

The seconds important difference is also related to the fact that a mock/spy is created with a context and the same instance is hold until the context shutdown. It can span across many tests or even test classes. It is important to properly reset/initialize mocks/spies manually before every test to avoid an impact of the operations done in previously executed tests. The issue has been already reported and hopefully will be resolved in the further Springockito versions.

Btw, in case of the following error:

org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.mockito.org/spring/mockito]
Offending resource: class path resource [yourSpringConfig.xml]
	at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
	at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
(...)

make sure the Springockito JAR has been successfully added as a project dependency.

In case you prefer annotations over XML Springockito has also something for you. This is a version of Springockito which allow to do similar things, but directly in your test code.

To use it in a project it is required to add an springockito-annatations.jar to your project dependencies.

With Maven:

<dependency>
    <groupId>org.kubek2k</groupId>
    <artifactId>springockito-annotations</artifactId>
    <version>1.0.2</version>
</dependency>

With Gradle:

testCompile "org.kubek2k:springockito-annotations:1.0.2"

(change 1.0.2 to the latest released version of springockito-annotation – the numeration is not synchronized with springockito – it is an independent jar (as of 1.0.2))

@ContextConfiguration(loader = SpringockitoContextLoader.class, locations = {<<the-base-configuration-file>>})
public class MockInjectionSpringockitoTest extends AbstractTestNGSpringContextTests {

    @Autowired
    private PlantWaterer plantWaterer;

    @WrapWithSpy
    @Autowired	//to inject a spy into this field to make a verification
    private WaterSource waterSource; //spy

    @ReplaceWithMock //just replace the original bean with a mock, will be null
                     //it won't be stubbed - no need to inject
    private WateringScheduler wateringScheduler; //mock

    @Test
    public void shouldSpyInjectedObject() {
        //given - mocks/spies are already created, can be stubbed here

        //when
        plantWaterer.waterPlants();

        //then
        verify(waterSource).startWaterFlow();
    }
}

The trick here is to use a custom Spring context loader which checks (by name) if there is any bean which should be replaced with a mock or wrapped with a spy.

The code above causes waterSource bean defined in a configuration file to be wrapped with a spy and wateringScheduler bean to be replaced with a mock (the original wateringScheduler bean will not be created at all). They are both injected into plantWaterer. @ReplaceWithMock and @WrapWithSpy annotations are used only by Springockito to detect which beans should be replaced/wrapped. To get an instance of a mock/spy (to stub it or verify behavior) it is needed to use also an appropriate annotation (@Autowired, @Resource or @Inject) – see waterSource in the previous listing.

There is a limitation which force to use the same field name as a bean which should be replaced/wrapped. It should be fixed in the future.

This post is the second part of the series Beyond the Mockito refcard extending recently released my Mockito reference card.

Some time ago I’ve got an idea to make a short document briefly presenting the most important Mockito features with the real life examples. It was targeted at people wanting to quickly learn more about Mockito framework and those who use Mockito from time to time and need a small example to recall a syntax of a given construction. The result of my work was recently released by DZone as the Mockito refcard. Six – ready to print – pages filled in with condensed knowledge, a lot of examples and practical advises.

Why? This is my another action to promote practices helping to write high quality code guided by tests. Besides it always takes me a while to introduce a mocking concept and Mockito itself to a new junior developer and it is quite repetitive job. Having a Mockito refcard I can give it to that person and later talk what he/she was learned and practice it during the pair programming sessions. Pure long-term time savings :).

As a supplement I also started a series of posts about Mockito, extending a refcard with the more advanced topics which did not fit into the base version.

I would like to take this opportunity to thank Paweł Lipiński who did a complete language review of a draft version and Brice Dutheil, Gordon Dickens and Tomek Kaczanowski for exchanging ideas how to make my refcard better. Krzysiek Jelski, Kamil Szymański, Marceli Kramarczuk and Kamil Żbikowski also contributed by reading a draft version and sending suggestions.

Writing the Mockito reference card I had an opportunity to take a closer look at the less popular, but very useful features of Mockito. Some of them were too advance or too rare in use to be described in a refcard which should be kept short. One of those things is SmartNull. Currently non void methods return “safe empty value” appropriate for known types (e.g.: 0, false, empty collection) or null in other cases. SmartNull to can be returned instead of pure null to receive a much more descriptive error message on NPE.

Instead of just a line when NullPointerException occurred:

java.lang.NullPointerException
    at PlantWaterer.generateNPE(PlantWaterer.java:24)
    at DefaultValuesTest.shouldReturnNicerErrorMessageOnNPE(DefaultValuesTest.java:64)

we have also got descriptive information what method was not stubbed:

org.mockito.exceptions.verification.SmartNullPointerException:
You have a NullPointerException here:
−> at PlantWaterer.generateNPE(PlantWaterer.java: 24)
because this method call was ∗not∗ stubbed correctly:
−> at PlantWaterer.generateNPE(PlantWaterer.java: 24)
wateringScheduler.returnNull();

    at PlantWaterer.generateNPE(PlantWaterer.java: 24)
    at DefaultValuesTest.shouldReturnNicerErrorMessageOnNPE(DefaultValuesTest.java:64)

A particular mock can be instructed to return SmartNull instead of the null value:

PlantWaterer plantWatererMock =
        mock(PlantWaterer.class, Mockito.RETURNS_SMART_NULLS);

or

@Mock(answer = Answers.RETURNS_SMART_NULLS)
private PlantWaterer plantWatererMock;

SmartNull will be probably the default bahavior in Mockito 2.0, but for the backward compatibility in 1.9.x it is necessary to tell every mock explicitly to use it. The need to write another piece of boilerplate code causes that almost nobody uses SmartNull despite it is a very useful feature. And there the second almost unknown element of Mockito enters the game – global configuration. Generally there is no need to configure Mockito. It just works. But for some rare cases the framework’s authors left a gate which allows to override the default configuration of a few core behaviors, including the default answer policy for unstubbed methods.

To make it work it is necessary to create org.mockito.configuration.MockitoConfiguration class (necessarily in that package) which implements IMockitoConfiguration interface. Usually it is comfortable to extend DefaultMockitoConfiguration class and only override desired behavior(s).

package org.mockito.configuration;

import org.mockito.internal.stubbing.defaultanswers.ReturnsSmartNulls;
import org.mockito.stubbing.Answer;

public class MockitoConfiguration extends DefaultMockitoConfiguration {

    public Answer<Object> getDefaultAnswer() {
        return new ReturnsSmartNulls();
    }
}

After that preparation we should get SmartNullPointerException with the verbose output instead of the pure NullPointerException for every mock in our module.

@Test(expectedExceptions = SmartNullPointerException.class)
public void shouldReturnNicerErrorMessageOnNPE() {
    //given
    //Mockito.RETURNS_SMART_NULLS not needed anymore
    WateringScheduler wateringSchedulerMock = mock(WateringScheduler.class);
    WaterSource waterSourceMock = mock(WaterSource.class);
    PlantWaterer plantWatererMock =
            new PlantWaterer(waterSourceMock, wateringSchedulerMock);

    //when
    plantWatererMock.generateNPE();

    //then
    //SmartNullPointerException exception expected
}

This post is the first part of the series Beyond the Mockito refcard.