jeudi 21 mars 2019

Spring Boot Unit testing endpoint NullPointerException - and how to reach 100% coverage

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?

Aucun commentaire:

Enregistrer un commentaire