0

I'm trying to mock a private method of my service with powermock by passing it the mockito matcher "eq" for its arguments. One of those argument is annotated with the @NotNull decorator from jetbrains.

When I run the test, I get the following error:

java.lang.IllegalArgumentException: Argument for @NotNull parameter X of Y must not be null

Target for testing

import org.jetbrains.annotations.NotNull;
...

class Service {
...
  private Map<String, Object> computeDataModel(User user, @NotNull Configuration configuration, Object providedDataModel) {...
}

Test Class

PowerMockito.when(service, "computeDataModel", eq(user), eq(configuration), eq(providedDataModel)).thenReturn(dataModel);

I also tried with any(Configuration.class) but without success.

Do you know how to process ? Thank you for your attention

Ugo Evola
  • 546
  • 3
  • 8
  • 19
  • `eq`, `any` and all other argument matchers always return `null`. – knittl Dec 16 '22 at 16:33
  • Does this answer your question? [PowerMockito is calling real method instead of mocked private one](https://stackoverflow.com/questions/42018713/powermockito-is-calling-real-method-instead-of-mocked-private-one) – knittl Dec 16 '22 at 16:34
  • 1
    You could try the `PowerMockito.doReturn(…).when(…)` form instead of `when(…).thenReturn(…)`. – knittl Dec 16 '22 at 16:35
  • Thanks @knittl that's work for me with PowerMockito.doReturn(…).when(…) – Ugo Evola Dec 16 '22 at 16:41
  • I just need to add @Spy on my service – Ugo Evola Dec 16 '22 at 16:43

1 Answers1

1

This has nothing to do with the annotation really, but with calling the real method with null values.

PowerMockito.when(service, "computeDataModel", eq(user), eq(configuration), eq(providedDataModel))
    .thenReturn(dataModel);

calls the real method.

eq is a matcher and returns null, effectively calling your method with 3 null arguments.

If you want to avoid calling your real method, you could use a different method of PowerMockito:

PowerMockito.doReturn(dataModel)
    .when(service, "computeDataModel", eq(user), eq(configuration), eq(providedDataModel));
knittl
  • 246,190
  • 53
  • 318
  • 364