package com.qxh.sb22;
import com.qxh.sb22.web.HelloController;
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.mock.web.MockServletContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
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;
// 告诉使用的Spring运行器
@RunWith(SpringRunner.class)
// 这是让整个测试运行在Spring Boot内置的容器中,
// 也可以使用普通的Servlet容器,比如Tomcat,Jetty
// 因此可以实际上以Servlet的方式启动应用程序,
// 也可以测试SpringMVC的正确性
@SpringBootTest(classes = {Sb22Application.class, MockServletContext.class})
@WebAppConfiguration
public class Sb22ApplicationTests {
/**
* 测试模拟myMvc
*/
private MockMvc mvc;
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(
new HelloController()
).build()
;
}
@Test
public void contextLoads() throws Exception {
// 模拟参数发起请求
ResultActionsactions = mvc.perform(MockMvcRequestBuilders.get(“/hello”).accept(MediaType.APPLICATION_JSON));
// 返回测试结果状态200
actions.andExpect(status().isOk())
// 返回的内容是Hello World
.andExpect(content().string(equalTo(“Hello World”)));
}
}