Skip to content
Advertisement

NPE while running test in Spring application (JUnit 5, Mockito 3, Spring JPA repositories)

I’m running a basic Spring App with Mockito 3.1.0 and and Junit 5.5.2. I have a Service call that includes two Spring Data JPA repositories. These are passed into the constructor for DI (along with two others that are immaterial – I’m including them in case they could also, potentially, cause errors.) I see no issues with the service when the app runs.

When I run my test, I get a NPE for myService. Stepping through the stack trace, hasn’t really shown me anything that relates to the error. I have also tried (following this Article: https://www.baeldung.com/mockito-junit-5-extension) updating my test class to look like this:

JavaScript

to no avail. What I suspect is happening is that something about my setup isn’t properly wired up – either as dependencies or syntax for DI.

How do I debug this? What am I missing? Thanks in advance!

Service:

JavaScript

Test:

JavaScript

Sample Repository:

JavaScript

Edit:

  • I forgot to mention that I have other files in this project that are using exactly these annotations (@RunWith(MockitoJUnitRunner.class), @Mock, @InjectMocks, @Before) that are not failing.
  • I updated the files with the relevant imports, and added an example of RepositoryN.
  • I update the MyService class to better reflect the parameters.

Advertisement

Answer

For anybody else who encounters this in the future, we were able to fix this problem by changing one of the imports from:

JavaScript

to

JavaScript

Edit:

  • This had to do with differing versions of JUnit. There’s a good long-form explanation as to why here.
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement