2

I'm learning to makes APIs. I'm trying to run a test on my Get request, but keep getting a Null Pointer Exception in my test class. What did I miss?

I'm using Spring Boot/Maven/Java 11. This is a very basic setup (as far as I know) as I have just begun to dip my toe into the world of Spring Boot.

Please see code below:

Controller Test Class:

package ControllerTest;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

public class StatControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testGetResponse()
            throws Exception {

        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders
                .get("/get");

        ResultMatcher contentMatcher = MockMvcResultMatchers.content()
                .string("GET Response");

        mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk());
    }
}

Controller Class:

package apiPackage;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
public class StatController {

    @RequestMapping("/")
    public String index(){
        return "Welcome to the SilverSnacks Stat Sheet!";
    }

    @GetMapping("/get")
    public @ResponseBody ResponseEntity<String> get(){
        return new ResponseEntity<String>("GET Response", HttpStatus.OK);
    }

    @GetMapping("/get/{id}")
    public @ResponseBody ResponseEntity<String> getById(@PathVariable String id){
        return new ResponseEntity<String>("GET Response:" + id, HttpStatus.OK);
    }

    @PutMapping("/put")
    public @ResponseBody ResponseEntity<String> put(){
        return new ResponseEntity<String>("PUT Response", HttpStatus.OK);
    }

    @PostMapping("/post")
    public @ResponseBody ResponseEntity<String> post(){
        return new ResponseEntity<String>("POST Response", HttpStatus.OK);
    }

    @DeleteMapping("/delete")
    public @ResponseBody ResponseEntity<String> delete(){
        return new ResponseEntity<String>("DELETE Response", HttpStatus.OK);
    }

    @PatchMapping("/patch")
    public @ResponseBody ResponseEntity<String> patch(){
        return new ResponseEntity<String>("PATCH Response", HttpStatus.OK);
    }
}

Error Output:

java.lang.NullPointerException
    at ControllerTest.StatControllerTest.testGetResponse(StatControllerTest.java:26)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
2
  • does test class has @RunWith and @WebMvcTest annotations? Commented Oct 8, 2019 at 16:13
  • No, I did not add those annotations at first. However, a comment below asked me to do. I did, and got another error. I did add the WebMvcTest annotation, and got yet another error. "Configuration error: found multiple declarations of @BootstrapWith for test class". Any idea why? Commented Oct 8, 2019 at 20:34

1 Answer 1

3

try to add the following annotation to the StatControllerTest

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class StatControllerTest {

    @Autowired
    private MockMvc mockMvc;
....
}
Sign up to request clarification or add additional context in comments.

2 Comments

I've added your suggested annotations, however I got yet another error. "Unable to find a @SpringBootConfiguration". Any idea why this is happening?
Ok, did a little more research and found that your answer was correct, but was missing one piece. "@SpringBootTest(classes = Application.class)". I needed to tell it where to find SpringBootConfiguration. Thanks for pointing me in the right direction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.