Marcin Zajaczkowski

About Marcin Zajaczkowski

Marcin is an experienced architect who specializes in creating high quality software. Being under the impression of the Agile methodologies and the Software Craftsmanship movement, he believes in the value of good, testable and maintainable code. He aims to forge good software that makes the client delighted and the team proud of how the code itself looks.

Mockito – Better error messages on NPE with globally configured SmartNull

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.

Reference: Beyond the Mockito refcard – part 1 – Better error messages on NPE with globally configured SmartNull from our JCG partner Marcin Zajaczkowski at the Solid Soft blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


2 − = one



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close