spring boot——MockMvc的用法 (SpringBoot 1.5.18)下测试通过
spring boot——MockMvc的用法
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 {
@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测试用例
@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);
}
}
原文地址:http://blog.51cto.com/mazongfei/2334045