0

I'm new to Spring Boot testing and I'm trying to test and endpoint. Following tutorials, I did this:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = SpringMiddlewareApplication.class)
@ComponentScan("com.springmiddleware")
@SpringBootTest
public class SpringMiddlewareApplicationTests {

private MockMvc mvc;

@Test
public void returnsString() {
    try {
        this.mvc.perform(get("/home")).andExpect(status().isOk())
        .andExpect(content().string(containsString("You are in the home page")));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

If I run the test it is passed, but the following error shows in the console:

java.lang.NullPointerException
at com.example.demo.SpringMiddlewareApplicationTests.returnsString

The RestController class is the following:

@RestController
public class FirstController {


    /**
     * Welcome page
     * 
     * @return String
     */
    @GetMapping("/home")
    public String homePage() {
        return "You are in the home page";
    }

What causes the error?
Also, even if this test passes, running Jacoco I do not have coverage for the method "homePage". How do I achieve this?

Usr
  • 2,628
  • 10
  • 51
  • 91

1 Answers1

0

Your object mvc is null! You test class must look like :

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = SpringMiddlewareApplication.class)
@ComponentScan("com.springmiddleware")
@SpringBootTest
public class SpringMiddlewareApplicationTests {

    private MockMvc mvc;

    @Autowired
    private FirstController firstController;

    @Before
    public void init() {
        mvc = MockMvcBuilders.standaloneSetup(firstController)
                .addPlaceholderValue("server.servlet.context-path", "example").build();

    }

    @Test
    public void returnsString() {
        try {
            this.mvc.perform(get("/home")).andExpect(status().isOk())
                    .andExpect(content().string(containsString("You are in the home page")));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Abder KRIMA
  • 3,418
  • 5
  • 31
  • 54
  • Thanks, it was always annotated with @Autowired in tutorials but that didn't work for me. Also, do you know how to do to make my method homePage() covered in jacoco? – Usr Mar 21 '19 at 13:19
  • I forget to show you the @Autowired object but i correct the post, check it again – Abder KRIMA Mar 21 '19 at 13:20