1.pom配置web
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency>
2.所需對象及Controllerspring
public class User { private String id; private String username; private Date birthday; public User(String id, String username) { this.id = id; this.username = username; } //get/set }
構造一個queryUserList服務mvc
@RestController @RequestMapping(value="/user") public class UserController { @GetMapping public List<User> queryUserList(){ //使用反射打印出信息 System.out.println(ReflectionToStringBuilder.toString(condition,ToStringStyle.MULTI_LINE_STYLE)); List<User> users = new ArrayList<>(); users.add(new User("1","張三")); users.add(new User("2","李四")); users.add(new User("3","王五")); return users; } }
編寫mockmvc測試用例app
@RunWith(SpringRunner.class) @SpringBootTest public class UserControllerTest { //僞造mvc環境 @Autowired private WebApplicationContext mac; private MockMvc mockMvc; @Before public void setup() { mockMvc = MockMvcBuilders.webAppContextSetup(mac).build(); } @Test public void whenGenInfoSuccess() throws Exception{ String result = mockMvc.perform(get("/user") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn().getResponse().getContentAsString(); System.out.println(result); } }