1.pom配置
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId>
</dependency>
2.所需对象及Controller
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服务
@RestController
@RequestMapping(value="/user")
public class UserController {@GetMappingpublic 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测试用例
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {//伪造mvc环境@Autowiredprivate WebApplicationContext mac;private MockMvc mockMvc;@Beforepublic void setup() {mockMvc = MockMvcBuilders.webAppContextSetup(mac).build();}@Testpublic 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);}
}
转载于:https://blog.51cto.com/mazongfei/2334046