The solution is simple. You mocked a class customerDataRepository but did not instruct it the mock what to do if the corresponding method is called. Mockito mocks then default back on doing nothing by method call and if there is a return value return null. Since your returned customerData is null you get your NPE when calling on this object. In your case this is in the error case that you get by calling getCustomerId().

To solve this issue simply instruct your mock

@Test
void removeCustomerDataWhenConsentIsNotGiven() {
   CustomerData customerDataTest = customerData;
   //when
   Mockito.when(customerDataRepository.findCustomerByDialogId(Mockito.any())).thenReturn(new CustomerData()); // <-- Add this line
   customerDataService.giveConsent(false,22L);
   //then 
   verify(customerDataRepository,times(1)).save(customerDataTest);
}

you can obviously replace Mockito.any() with Mockito.anyInt() or 42 and new CustomerData() with a object you previously created. I think you get the idea ;)

Answer from GJohannes on Stack Overflow
Top answer
1 of 2
5

The solution is simple. You mocked a class customerDataRepository but did not instruct it the mock what to do if the corresponding method is called. Mockito mocks then default back on doing nothing by method call and if there is a return value return null. Since your returned customerData is null you get your NPE when calling on this object. In your case this is in the error case that you get by calling getCustomerId().

To solve this issue simply instruct your mock

@Test
void removeCustomerDataWhenConsentIsNotGiven() {
   CustomerData customerDataTest = customerData;
   //when
   Mockito.when(customerDataRepository.findCustomerByDialogId(Mockito.any())).thenReturn(new CustomerData()); // <-- Add this line
   customerDataService.giveConsent(false,22L);
   //then 
   verify(customerDataRepository,times(1)).save(customerDataTest);
}

you can obviously replace Mockito.any() with Mockito.anyInt() or 42 and new CustomerData() with a object you previously created. I think you get the idea ;)

2 of 2
1

Assuming that you have just corrected method names before posting it to Stackoverflow, and method you are calling in the test: giveConsent is, actually, the same method as methodTotest of the CustomerDataService.

Before calling customerDataService.giveConsent(false,22L);, you need to configure you repository to return some test (not null! or mocked) customerData entity:

when(customerDataRepository.findCustomerByDialogId(22L)).thenReturn(customerDataTest);
customerDataService.giveConsent(false,22L);

Note: since you are passing false as 1st variable, you will get to this branch of code

    if (!consent) {  
      customerDataRepository.deleteById(customer.getCustomerId());
    }

And in the test you are expecting save() method to be called, so the test will fail.

Discussions

Method `Only.verify` throws `NullPointerException`
java.lang.NullPointerException: Cannot invoke "org.mockito.invocation.Invocation.getMock()" because "undesired" is null at org.mockito.internal.exceptions.Reporter.noMoreInteractionsWanted(Reporter.java:555) at org.mockito.internal.verification.Only.verify(Only.java:30) at org.mockito.inte... More on github.com
🌐 github.com
0
January 17, 2024
java - Mockito @Mock and @InjectMocks are null - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
How do I avoid the NullPointerException in Mockito, jUnit testing?
I think calling mock(YourClass.class) returns a mock which upon calling its methods throws a NPE. This mean you should explicitly use doCallRealMethod(yourMock).when(yourMethod()) if you want the mock's method to behave like it normally would. By calling Mockito.spy(YourClass.class) it will create a mock which by default uses the real methods, if you don't specify otherwise More on reddit.com
🌐 r/javahelp
5
1
August 16, 2017
NullPointerException when using Mockito - OpenMRS Talk
I am trying to write a unit test in JUnit with Mockito however am geting a NPE when I inject-mocks…here is the Unit test https://github.com/openmrs/openmrs-module-sync2/commit/3dec2022a0d5058c45fce3f9abdc106ce0b8c833 and… More on talk.openmrs.org
🌐 talk.openmrs.org
0
October 24, 2019
🌐
GitHub
github.com › mockito › mockito-kotlin › issues › 255
Getting a null pointer exception when invoking a method on a mock · Issue #255 · mockito/mockito-kotlin
May 18, 2018 - When I mock this class in java, I get a null pointer exception. Foo foo = Mockito.mock(Foo.class); when(foo.print()).thenReturn("value"); // Null pointer exception saying bar is null.
Author: mockito
🌐
GitHub
github.com › mockito › mockito › issues › 3237
Method `Only.verify` throws `NullPointerException` · Issue #3237 · mockito/mockito
January 17, 2024 - A quick analysis shows that it is caused by method Only.verify which searches for an optional unverified invocation by execution of method InvocationsFinder.findFirstUnverified, but then fails to check for the result for null and just calls method Reporter.noMoreInteractionsWanted which throws the exception because the invocation was not found. https://github.com/mockito/mockito/blob/main/src/main/java/org/mockito/internal/verification/Only.java#L29C37-L30
Author: mockito
🌐
Stack Overflow
stackoverflow.com › questions › 75157348 › mockito-mock-and-injectmocks-are-null
java - Mockito @Mock and @InjectMocks are null - Stack Overflow
Your TeamService class has an explicit constructor. That may be interfering with Mockito. Why not explicitly create instances in a @BeforeEach method? The mock should already be set at that time.
🌐
Reddit
reddit.com › r/javahelp › how do i avoid the nullpointerexception in mockito, junit testing?
r/javahelp on Reddit: How do I avoid the NullPointerException in Mockito, jUnit testing?
August 16, 2017 -
@Test
    public void testAddJobDescription()throws InvalidInputException
    {
        NewJobDescription newJobDescription = mock(NewJobDescription.class);
                
        User user = new User();
        
        when( jobDescriptionService.addJobDescription( newJobDescription, user ) ).thenReturn( new JobDescription());
       
        assertEquals( new JobDescription().getExperience(), jobDescriptionService.addJobDescription( newJobDescription, user ).getExperience() );
        
    }

Why wouldn't the when().thenReturn() clause work here? There shouldn't be any exception thrown here.

🌐
Coderanch
coderanch.com › t › 739460 › frameworks › NullPointerException-run-unit-test-Spring
Getting NullPointerException when run unit test using Spring boots, JUnit 5 and Mockito (Spring forum at Coderanch)
February 16, 2021 - I'm using @AutoConfigureMockMvc but still getting NullPointerException. ... Try to make it as @SpringBootTest instead of @WebMvcTest to see if you have that issue. ... Hi, I am facing same issue, when mocked service bean is null. Was this issue solved ? If so, could you please provide the solution that worked. Thanks ... when mocked service bean is null Are you sure your service bean is annotated as a component?
🌐
OpenMRS
talk.openmrs.org › t › nullpointerexception-when-using-mockito › 25209
NullPointerException when using Mockito - OpenMRS Talk
October 24, 2019 - I am trying to write a unit test in JUnit with Mockito however am geting a NPE when I inject-mocks…here is the Unit test https://github.com/openmrs/openmrs-module-sync2/commit/3dec2022a0d5058c45fce3f9abdc106ce0b8c833 and…
Find elsewhere
🌐
Coderanch
coderanch.com › t › 750685 › engineering › Null-Pointer-exception-Unit-Test
Null Pointer exception in Unit Test (Testing forum at Coderanch)
java.lang.NullPointerException: Cannot invoke "com.example.onlinehotelbookingsystem.service.RoomService.findByHotelId(java.lang.Long)" because "this.roomService" is null at com.example.onlinehotelbookingsystem.service.impl.AccommodationServiceImpl.lambda$findById$0(AccommodationServiceImpl.java:56) at java.base/java.util.Optional.map(Optional.java:260) at com.example.onlinehotelbookingsystem.service.impl.AccommodationServiceImpl.findById(AccommodationServiceImpl.java:52) at com.example.onlinehotelbookingsystem.service.impl.AccommodationServiceImplTest.whenFindById_verifyThatIsNotNull(Accommoda
🌐
Stack Overflow
stackoverflow.com › questions › 76375007 › how-do-i-fix-a-null-pointer-exception-in-a-junit-test-class-when-using-mockito
java - How do I fix a null pointer exception in a JUnit test class when using Mockito? - Stack Overflow
*/ @Spy private FileRepository fileRepository; @InjectMocks RunSummaryServiceImpl runSummaryServiceImpl; @Before public void setup() { MockitoAnnotations.initMocks(this); } @Test public void TestprocessCustomerRunSummaries() { final RunSummaryServiceImpl runSummaryServiceImpl = new RunSummaryServiceImpl(); final Collection<RunSummary> runs = new ArrayList<>(); runs.add(new RunSummary("customer1", 1, Timestamp.valueOf("2023-05-30 10:00:00"))); runs.add(new RunSummary("customer2", 2, Timestamp.valueOf("2023-05-30 11:00:00"))); runs.add(new RunSummary("customer3", 3, Timestamp.valueOf("2023-05-30 12:00:00"))); runSummaryServiceImpl.processCustomerRunSummaries(runs); //NULL POINTER EXCEPTION HERE } }
🌐
Fix the bugs
fixthebugs.com › home › fixed bugs › junit: java.lang.nullpointerexception: cannot invoke “[ljava.lang.class;.clone()” because ” .parametertypes” is null
JUnit: java.lang.NullPointerException: Cannot invoke "[Ljava.lang.Class;.clone()" because " .parameterTypes" is null - Fix the bugs
March 5, 2024 - java.lang.NullPointerException: Cannot invoke "[Ljava.lang.Class;.clone()" because " .parameterTypes" is null · Solution: The problem is that you are mocking a java.lang.* object. Explanation: Mockito is based on java.lang.* so you can’t mock it.
🌐
Codepills
codepills.com › 2018 › 05 › 10 › 3-basic-mistakes-for-nullpointerexception-when-mock
3 basic mistakes for NullPointerException when Mock | CodePills.com
May 10, 2018 - NOTE: just exclude if any syntax exceptions it might be my typing mistakes. every thing is fine just getting NullpointerException. i declared MockMvc object also bt didn’t mension here · when debugging in StockController i am getting null pointer Exception in —-> if (optional.isPresent()) ... From first glance, I think your problem is with the Spring application context. You are running a Mock test with @RunWith(MockitoJunitRunner.class).
🌐
Medium
medium.com › @luketong › how-to-avoid-nullpointerexceptions-when-using-mockito-in-junit-5-dbb348d99232
How to Avoid NullPointerExceptions When Using Mockito in JUnit 5 | by Technical Life | Medium
November 13, 2023 - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) public class MyTest { @Mock private MyDependency myDependency; private MyDelegate myDelegate = new MyDelegate(myDependency); @Test public void myTest() { // Set up the mock behavior using when() when(myDependency.callMethod()).thenReturn(true); // Invoke the method under test myDelegate.doSomething(); } } class MyDelegate{ public MyDelegate(MyDependency myDependency) { this.myDependency = myDependency; } myDependency.callMethod(); }
🌐
GitHub
github.com › mockito › mockito › issues › 2026
NullPointerException in java.lang.reflect.Method.getParameterTypes · Issue #2026 · mockito/mockito
August 27, 2020 - - in core.rest.exception.mapper.NotFoundExceptionMapperTest [ERROR] testExceptionCreatesServerErrorResponseWhenEndpointWasNotMatchedAndIsServiceRequest Time elapsed: 0.012 s <<< ERROR! java.lang.NullPointerException at java.base/java.lang.reflect.Method.getParameterTypes(Method.java:311) at org.mockito.internal.creation.DelegatingMethod.<init>(DelegatingMethod.java:20) at org.mockito.internal.invocation.DefaultInvocationFactory.createMockitoMethod(DefaultInvocationFactory.java:80) at org.mockito.internal.invocation.DefaultInvocationFactory.createInvocation(DefaultInvocationFactory.java:59) at
Author: mockito
🌐
Stack Overflow
stackoverflow.com › questions › 75823161 › spring-webclient-mockito-nullpointerexception-body-is-null
Spring WebClient - Mockito NullPointerException body() is null - Stack Overflow
Your mocking won't work, the one where you mock the .body call won't actually match the parameters as the Mono.just is another instance as the Mono.just in the method and thus doesn't match, hence Mockito will return null.
🌐
Stack Overflow
stackoverflow.com › questions › 73044471 › getting-nullpointerexception-because-mockito-variable-is-set-to-null-even-though
java - Getting nullPointerException because Mockito variable is set to null even though I have mocked it - Stack Overflow
As you are using IOC to inject the SolrClient (@Resource annotation), you need to inject the mock in your ShowService instance during the test. There are different solutions, but the more convenient in your case would be to use the Mockito Extension ...
🌐
Stack Overflow
stackoverflow.com › questions › 74669313 › mockito-test-with-spring-controller-null-pointer-exception
java - Mockito test with Spring Controller Null Pointer Exception - Stack Overflow
java.lang.NullPointerException: ...t.addTeacherPostNonExistingTeacher(TeacherControllerMockTest.java:59) You run a Spring Boot test and autowire your field and that's it....