今日学习SpringBoot教程,但是在做单元测试时遇到一个问题,status()、content()、equalTo()报错,百思而不知其解,于是终于在网上找到了解决办法,这时便记录下来。
HelloTests类代码
package com.neo.SpringBoot;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.neo.SpringBoot.controller.HelloWorldController;
@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloTests {
private MockMvc mvc;
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build();
}
@Test
public void getHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Hello World")));
}
}
HelloWorldController类代码
package com.neo.SpringBoot.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
@RequestMapping("/hello")
public String index() {
return "Hello World";
}
}
需要导入的方法
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
本文详细介绍了在SpringBoot项目中进行单元测试时遇到的问题及解决方案,重点讲解了如何正确使用status(), content() 和equalTo()方法来验证HTTP响应状态码及返回内容。
1990

被折叠的 条评论
为什么被折叠?



