Spring Boot Unit测试端点NullPointerException - 以及如何达到100%覆盖率

问题描述 投票:0回答:1

我是Spring Boot测试的新手,我正在尝试测试和端点。按照教程,我这样做了:

@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();
    }
}

如果我运行测试,则会传递,但控制台中会显示以下错误:

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

RestController类如下:

@RestController
public class FirstController {


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

是什么导致错误? 此外,即使这个测试通过,运行Jacoco我没有覆盖方法“homePage”。我该如何实现这一目标?

spring-boot testing junit jacoco jacoco-maven-plugin
1个回答
0
投票

你的对象mvc是null!你测试类必须看起来像:

@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();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.