单元测试,模拟用户Get登陆,并携带登录后的token访问接口
HttpClient _httpClient; HttpClient _businessHttpClient; private async Task<string> GetAccessToken() { _businessHttpClient = new HttpClient(); _businessHttpClient.BaseAddress = new Uri("http://localhost:8998/Meet.WebApi/"); _httpClient = new HttpClient(); _httpClient.BaseAddress = new Uri("http://localhost:8998/HRManage.WebApi/api/UserLogin?username=admin&password=111111"); var parameters = new Dictionary<string, string>(); parameters.Add("username", "admin"); parameters.Add("password", "111111"); var response = await _httpClient.PostAsync(_httpClient.BaseAddress, new FormUrlEncodedContent(parameters)); var responseValue = await response.Content.ReadAsStringAsync(); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var data = JsonConvert.DeserializeObject<ResultEntity<UserLoginResultDTO>>(responseValue); return data.Data.AccessToken; } else { return string.Empty; } } [TestMethod] public void GetMeetingById() { string tokenstring = GetAccessToken().Result; _businessHttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenstring); var response = _businessHttpClient.GetAsync("Meet/GetMeetingById?Id=5C0062FF-542A-4C6E-BE28-5998EC3CEDE4").Result; var responseValue = response.Content.ReadAsStringAsync().Result; _businessHttpClient.Dispose(); var data = JsonConvert.DeserializeObject<ResultEntity<MeetingOutDto>>(responseValue); Assert.AreEqual(true, JObject.Parse(responseValue)["IsSuccess"].Value<bool>(), JObject.Parse(responseValue)["Msg"].Value<string>()); }
Post方式:
HttpClient _httpClient; //模拟登陆 public async Task<bool> Login() { _httpClient = new HttpClient(); _httpClient.BaseAddress = new Uri("http://localhost:8088");//14199 //9011 LoginInput log = new LoginInput() { mobile = "13981711707", pwd = "123123" }; HttpContent httpcontent = new StringContent(JsonConvert.SerializeObject(log)); httpcontent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var response = await _httpClient.PostAsync("hcApi/Login/login", httpcontent); var responseValue = await response.Content.ReadAsStringAsync(); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return JObject.Parse(responseValue)["isOK"].Value<bool>(); } else { return false; } } /// <summary> /// 根据条件获取卫生院信息 /// </summary> /// <returns></returns> [TestMethod] public async Task GetHealthCenterInfo() { await Login(); var response = await _httpClient.GetAsync("hcApi/SampleEntry/GetHealthCenterInfo?hcID=57&&keyWord=&&pageIndex=1&&pageSize=10"); var responseValue = await response.Content.ReadAsStringAsync(); _httpClient.Dispose(); Assert.AreEqual(0, JObject.Parse(responseValue)["errorCode"].Value<int>(), JObject.Parse(responseValue)["msg"].Value<string>()); }