Spring 引导单元测试端点 NullPointerException - 以及如何达到 100% 的覆盖率

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

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

@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 class 如下:

@RestController
public class FirstController {


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

错误原因是什么?
此外,即使此测试通过,运行ning Jacoco I 也没有覆盖方法 "homePage"。我该如何实现?

您的对象 mvc 为空! 你测试 class 必须看起来像 :

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