测试类实例
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = HelloApplication.class)
@WebAppConfiguration
public class HelloApplicationTests (
private MockMvc mvc;
@Before
public void setOp() throws Exception {
mvc = MockMvcBuilders. standaloneSetup (new HelloController ()) . build() ;
}
@Test
public void hello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/hello") .accept(MediaType.
APPLICATION_JSON)) .andExpect(status() .isOk())
.andExpect (content() . string (equal To ("Hello World")));
}
代码解析如下
• @RunWith(SpringJUnit4ClassRunner.class): 引入Spring对JUnit4的支持。
• @SpringApplicationConfiguration (classes = HelloApplication.class): 指定Spring Boot的启动类。
• @WebAppConfiguration: 开启Web应用的配置, 用于模拟ServletContext。
• MockMvc对象: 用于模拟调用 Controller的接口发起请求, 在@Test定义的hello测试用例中, perform函数执行 一次请求调用, accept用于执行接收的数据类型,andExpect用于判断接口返回的期望值。
• @Before: JUnit中定义在测试用例@Test内容执行前预加载的内容, 这里用来初始化对HelloController的模拟 。
注意引入下面的静态引用, 让status、 content、 equalTo函数可用:
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;