1.上一篇博客是初步创建了springboot。接下来咱们编写测试用例来测试springboot的运行结果。java
2.在 test/java 目录下创建一个测试用例类web
package com.myspringboot.study; import com.myspringboot.web.HelloController; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 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 static org.hamcrest.core.IsEqual.equalTo; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @SpringBootTest(classes=HelloController.class) @AutoConfigureMockMvc public class StudyApplicationTests { @Test public void contextLoads() { } @Autowired private MockMvc mvc; @Test public void getHello() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("hello world"))); } }
上面的SpringBootTest(classes=)指向的是测试的controllerspring
而下面的getHello方法,是经过模拟请求 /hello 地址,判断他的状态和他的返回结果。springboot
注意事项 :mvc
创建测试用例的SpringBootTest(classes)所指向的类,他的目录必定要在最外面,如目录是在com.study下,若是你想测试com目录下的类,是测试不了的,由于springboot的规则是扫描SpringBootTest(classes)所在目录及子目录的类,这点注意一下。测试