@SpringBootTest
class UserTest{
@Autowired
WebApplicationContext webApplicationContext;
private static final String baseUrl = "/user";
private MockMvc mvc;
private HttpHeaders httpHeaders;
private RequestBuilder request;
/**初始化测试环境*/
@BeforeEach
public void before(){
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
MultiValueMap<String, String> headMap = new LinkedMultiValueMap<>();
headMap.add("Authorization", "e8a902c11e4e5eadeafd0e6fc5fc97c1");
headMap.add("Content-Type", "application/json; charset=utf-8");
httpHeaders = new HttpHeaders();
httpHeaders.addAll(headMap);
request = null;
}
/**接口返回结果*/
@AfterEach
public void after() throws Exception {
ResultActions resultActions = mvc.perform(request)
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
MockHttpServletResponse response = resultActions.andReturn().getResponse();
response.setCharacterEncoding("UTF-8");
resultActions.andDo(print());
}
/** 测试传入参数*/
@Test
void user() {
request = MockMvcRequestBuilders.get(baseUrl + "/user")
.param("id", "1")
.param("name", "admin")
.param("password","123456")
.headers(httpHeaders);
}
/** 测试传入的是对象*/
@Test
void user() {
Map<String,Object>map = new HashMap<>();
map.put("id","1");
map.put("name","admin");
map.put("password","123456");
request = MockMvcRequestBuilders.post(baseUrl + "/user")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.content(JSONObject.toJSONString(map))
.headers(httpHeaders);
}
}
|