cybertextron cybertextron - 3 months ago 45
Java Question

NullPointer exception in a Spring Rest Controller test - Java

I have the following

Rest Controller
and unit test in Spring-Boot 1.4:

HealthChecker controller:



@RestController
public class HealthCheckerController {

@Autowired
private InstanceRepository instanceRepository;

@RequestMapping(value = "/healthchecker", method = RequestMethod.GET)
@ResponseBody
public List<Instance> findAll() {
return this.instanceRepository.findAll();
}


HealthCheckerControllerTest:



@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@WebAppConfiguration
public class HealthCheckerControllerTest {

private MockMvc mvc;

@Autowired
private InstanceRepository instanceRepository;

@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(new HealthCheckerController()).build();

this.instanceRepository.deleteAll();
Instance first = new Instance("10.20.30.40", "ami-xxxxxxxx");
Instance second = new Instance("10.20.30.41", "ami-xxxxxxxx");
this.instanceRepository.save(first);
this.instanceRepository.save(second);

for (Instance instance : this.instanceRepository.findAll()) {
System.out.println(instance);
}
}

@Test
public void testHealthChecker() throws Exception {
mvc.perform(get("/healthchecker")).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].ipaddress", is("10.20.30.40")))
.andExpect(jsonPath("$[0].ami", is("ami-xxxxxxxx")))
.andExpect(jsonPath("$[1].ipaddress", is("10.20.30.41")))
.andExpect(jsonPath("$[1].ami", is("ami-xxxxxxxx")));
}
}


However, when I execute the unit tests, it's giving me the following error:

Tests run: 21, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 19.83 sec <<< FAILURE! - in TestSuite
testHealthChecker on testHealthChecker(cloudos.HealthCheckerControllerTest)(cloudos.HealthCheckerControllerTest) Time elapsed: 0.193 sec <<< FAILURE!
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at cloudos.HealthCheckerController.findAll(HealthCheckerController.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
at cloudos.HealthCheckerControllerTest.testHealthChecker(HealthCheckerControllerTest.java:48)


Accessing that from the UI works just fine:

[{"ipaddress":"10.20.30.40","ami":"ami-xxxxxxxx"},{"ipaddress":"10.20.30.41","ami":"ami-xxxxxxxx"}]


I understand the problem is that
private InstanceRepository instanceRepository
is not being initialized in the
unit test
, so when it's accessed inside the
HealthCheckerController
it's null, however that's not the purpose of
@Autowired
?
How could I fix this problem?

Answer

When you are using MockMvcBuilders.standaloneSetup you need to manually setup your controller object (it's rather for unit testing)

If you want to use full Spring context (with all @Autowired fields available) you will need to use MockMvcBuilders.webAppContextSetup

This should work:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@WebAppConfiguration
public class HealthCheckerControllerTest {

    private MockMvc mvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    private InstanceRepository instanceRepository;

    @Before
    public void setUp() throws Exception {

        mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

        this.instanceRepository.deleteAll();
        Instance first = new Instance("10.20.30.40", "ami-xxxxxxxx");
        Instance second = new Instance("10.20.30.41", "ami-xxxxxxxx");
        this.instanceRepository.save(first);
        this.instanceRepository.save(second);

        for (Instance instance : this.instanceRepository.findAll()) {
            System.out.println(instance);
        }
    }

    @Test
    public void testHealthChecker() throws Exception {
        mvc.perform(get("/healthchecker")).andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(jsonPath("$", hasSize(2)))
                .andExpect(jsonPath("$[0].ipaddress", is("10.20.30.40")))
                .andExpect(jsonPath("$[0].ami", is("ami-xxxxxxxx")))
                .andExpect(jsonPath("$[1].ipaddress", is("10.20.30.41")))
                .andExpect(jsonPath("$[1].ami", is("ami-xxxxxxxx")));
    }
}

You could eventually try to add constructor to your controller and manually inject existing repository to newly created controller:

@RestController
public class HealthCheckerController {

    @Autowired
    private InstanceRepository instanceRepository;

    public HealthCheckerController(InstanceRepository instanceRepository) {
        this.instanceRepository = instanceRepository;
    }

    @RequestMapping(value = "/healthchecker", method = RequestMethod.GET)
    @ResponseBody
    public List<Instance> findAll() {
        return this.instanceRepository.findAll();
    }
}

and your mvc configuration should look like this:

mvc = MockMvcBuilders.standaloneSetup(new HealthCheckerController(instanceRepository)).build();