Skip to content
Advertisement

NullPointerException Mock when use RestTemplate

I am new to using mockito and I have a problem. I wrote a controller test and it uses restTemplate to get data from another api, but when I run the test, the variable of this type is null. In result NullPointerException.

What could be the problem?

Controlle:

JavaScript

Test:

JavaScript

Advertisement

Answer

This is because you don’t have restTemplate, so restTemplate is null.

To initialise this, in the test:

  • You need to declare restTemplate. E.g.
JavaScript
  • Then you need to inject this to your mockMvc. E.g.
JavaScript

In case of you’re not writing test using the annotation style like this. You can do:

JavaScript

P/S: If mockMvc is the one you’re gonna test, so don’t name it as prefix mock, it’s confused.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement