Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this short tutorial, we’ll use Mockito to check if null is passed as an argument to a method. We’ll see how to match null directly and by using ArgumentMatchers.

2. Example Setup

First, let’s create a simple Helper class with a lone concat() method returning the concatenation of two Strings:

class Helper {

    String concat(String a, String b) {
        return a + b;
    }

}

We’ll now add a Main class. Its method methodUnderTest() calls concat() to concatenate the String Baeldung with null:

class Main {

    Helper helper = new Helper();

    String methodUnderTest() {
        return helper.concat("Baeldung", null);
    }

}

3. Using Only Exact Values

Let’s set up the test class:

class MainUnitTest {

    @Mock
    Helper helper;

    @InjectMocks
    Main main;

    @BeforeEach
    void openMocks() {
        MockitoAnnotations.openMocks(this);
    }

    // Add test method

}

We created a mocked Helper thanks to @Mock. Then we injected it into our Main instance via @InjectMocks. Lastly, we invoked MockitoAnnotations.openMocks() to enable Mockito annotations.

We aim to write a unit test to verify that methodUnderTest() delegates to concat(). Additionally, we want to ensure that the second argument is null. Let’s keep it simple and check that the first argument of the call is Baeldung while the second one is null:

@Test
void whenMethodUnderTest_thenSecondParameterNull() {
    main.methodUnderTest();
    Mockito.verify(helper)
      .concat("Baeldung", null);
}

We called Mockito.verify() to check that the argument values were the expected ones.

4. Using Matchers

We’ll now use Mockito’s ArgumentMatchers to check the passed values. As the first value is irrelevant in our example, we’ll use the any() matcher: thus, any input will pass. To check that the second parameter is null, we can simply use isNull():

@Test
void whenMethodUnderTest_thenSecondParameterNullWithMatchers() {
    main.methodUnderTest();
    Mockito.verify(helper)
      .concat(any(), isNull());
}

5. Conclusion

In this article, we learned how to verify that the argument passed to a method is null with Mockito. We did this both by checking exact values and by using ArgumentMatchers.

As always, the code is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.