Parameter specified as non-null is null mockito

Mockito: Dealing with Non-Null Parameters that are Null

When using Mockito, if a non-null parameter is specified but passed as null during a method call, by default Mockito will throw a NullPointerException. This behavior can be modified by using certain Mockito methods.

One way to handle this situation is to use the Optional class. This class is part of the Java 8 libraries and provides a way to represent an optional value. Here’s an example:

    
      public String processString(Optional<String> input) {
          if (input.isPresent()) {
              // Process the input string
              return "Processed: " + input.get();
          } else {
              // Handle the null case
              return "Input is null";
          }
      }
    
  

With this approach, you can pass the parameter as an Optional and check for its presence using the isPresent() method. If the input is present, you can perform the desired operations using the get() method. Otherwise, you can handle the null case appropriately.

To mock this method using Mockito, you can use the Optional class as well. Here’s an example:

    
      // Create a mock instance
      MyService myService = Mockito.mock(MyService.class);
  
      // Create the expected return value
      Optional<String> expectedOutput = Optional.of("Expected Output");
  
      // Set up the mock behavior
      Mockito.when(myService.processString(Mockito.any())).thenReturn(expectedOutput);
  
      // Perform the method call
      Optional<String> actualOutput = myService.processString(Optional.empty());
  
      // Verify the expected behavior
      Assert.assertEquals(expectedOutput, actualOutput);
    
  

In this example, we create a mock instance of the MyService class using Mockito. We then define the expected return value as an Optional instance. To set up the mock behavior, we use Mockito.when and specify any input parameter using Mockito.any(). Finally, we call the method with an empty Optional as the parameter, and verify that the actual output matches the expected output.

By using Optional and Mockito, you can easily handle non-null parameters that are passed as null, and define the desired behavior for your mocked methods.

Leave a comment