我有一个ApiController,其中有2个调用,用于从外部APis获取响应-httpClient.PostAsync和httpClient.GetAsync。
我可以得到一些有关UnitTesting(Nunit)的建议-httpClient.PostAsync和httpClient.GetAsync交互。
下面的代码段-
[System.Web.Http.RoutePrefix("api/v1/testApi")]
[System.Web.Http.AllowAnonymous]
public class TestApiController : ApiController
{
//get settings data from config file -TestFetchTokenLogin , TestFetchTokenKey , TestFetchTokenUri etc
[System.Web.Http.Route("gettestapi")]
[ValidateAntiForgeryToken]
public IHttpActionResult GetTestAPI(string param1 = "", string param2 = "", string param3 = "", string param4 = "")
{
ApiDataResponse dataResponse;
var httpClient = new HttpClient(new HttpClientHandler { UseProxy = false });
try
{
List<KeyValuePair<string, string>> fetchTokenrequest = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("login", TestFetchTokenLogin),
new KeyValuePair<string, string>("password", TestFetchTokenKey)
};
FormUrlEncodedContent fetchTokenrequestBody = new FormUrlEncodedContent(fetchTokenrequest);
var fetchTokenResponse = httpClient.PostAsync(TestFetchTokenUri, fetchTokenrequestBody);
if (fetchTokenResponse != null)
{
var tokenResponse = JToken.Parse(fetchTokenResponse.Result.Content.ReadAsStringAsync().Result);
var token = tokenResponse?.SelectToken("access_token")?.ToString();
if (!string.IsNullOrWhiteSpace(token))
{
var apiResponse = httpClient.GetAsync($"{TestFetchDataUri}?restapi.session_key={token}¶m1={param1}¶m2={param2}&sub_param2={param3}¶m4={param4}&OutputFormat=json");
var task = apiResponse.Result.Content.ReadAsStringAsync();
dataResponse = new ApiDataResponse
{
Success = true,
Response = task.Result
};
return ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, dataResponse));
}
dataResponse = new ApiDataResponse
{
Success = false,
Response = "access_token not exists in the response"
};
return ResponseMessage(Request.CreateResponse(HttpStatusCode.NoContent, dataResponse));
}
dataResponse = new ApiDataResponse
{
Success = false,
Response = "token response empty or null"
};
return ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, dataResponse));
}
catch (Exception ex)
{
dataResponse = new ApiDataResponse
{
Success = false,
Response = ex.Message
};
return ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, dataResponse));
}
}
}
}
答案 0 :(得分:0)
我建议将api功能和您的逻辑分开。
将两个http调用都移至逻辑,并在构造函数中创建HttpClient,不要忘记处理。
原因: 1.您可以编写路由测试而无需实现所有HttpClient的东西 2.您可以使用模拟的http处理程序测试您的HttpClient调用(发布,获取),也可以模拟HttpClient->如果通过逻辑中的构造函数注入它们,则两者都可以
请正确实施异步-等待模式。
我进行了快速拆分-我将处理这样的逻辑(请参见下文),并从api调用此逻辑。
public class TestLogic : IDispose {
private HttpClientHandler _Handler;
// I would handle the login and password in a own config object
public TestLogic(HttpClientHandler handler, Config config )
{
_Handler = handler ?? throw new ArgumentException();
}
public async Task<ApiDataResponse> PostfetchTokenrequestBodyAsync()
{
List<KeyValuePair<string, string>> fetchTokenrequest = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("login", TestFetchTokenLogin),
new KeyValuePair<string, string>("password", TestFetchTokenKey)
};
FormUrlEncodedContent fetchTokenrequestBody = new FormUrlEncodedContent(fetchTokenrequest);
var fetchTokenResponse = await httpClient.PostAsync(TestFetchTokenUri, fetchTokenrequestBody).ConfigurationAwait(false);
fetchTokenResponse.EnsureSuccessStatusCode();
var tokenResponse = JToken.Parse(await fetchTokenResponse.ReadAsStringAsync().ConfigurationAwait(false));
var token = tokenResponse?.SelectToken("access_token")?.ToString();
return tokenResponse;
}
public async Task<ApiDataResponse> GetHinterlandFetchDataUriAsync(string token, ...)
{
var apiResponse = httpClient.GetAsync($"{HinterlandFetchDataUri}?restapi.session_key={token}¶m1={param1}¶m2={param2}&sub_param2={param3}¶m4={param4}&OutputFormat=json");
apiResponse.EnsureSuccessStatusCode(); // handle exception
var result = await apiResponse.Result.Content.ReadAsStringAsync().ConfigurationAwait(false);
return = new ApiDataResponse
{
Success = true,
Response = result
};
}
// implement IDisposable interface correct https://docs.microsoft.com/de-de/dotnet/api/system.idisposable?view=netframework-4.7.2
}