У меня есть 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));
}
}
}
}