我的asp.net core 项目里面大部分功能都是去调用别人的API ,大量使用HttpClient,公司单元测试覆盖率要求95%以上,很难做到不mock HttpClient 达到这个指数。
以下方法是我自己总结的在单元测试里 mock httpClient 的方式,基本思路是利用集成测试框架,mock外部调用的API ,达到httpClient 代码的覆盖。
代码地址:https://github.com/Halo-Shaka/LearningAspNetCoreIntegrationTesting.git
举个例子,创建一个简单的asp.net core 项目,里面只有一个api , api/values, 是个get 方法,
get 方法内部是去调用外部API, 随便写个方法 向google 发一个信息。
[Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { private readonly IHttpClientFactory _httpClientFactory; private readonly IOptions<AppSettings> _options; public ValuesController(IHttpClientFactory httpClientFactory, IOptions<AppSettings> options) { _httpClientFactory = httpClientFactory; _options = options; } // GET api/values [HttpGet] public async Task<ActionResult> Get() { var client = _httpClientFactory.CreateClient(); var url = _options.Value.Url; var payload = new { From = "China" }; var requestMessage = new HttpRequestMessage(HttpMethod.Post, url) { Content = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json") }; try { var response = await client.SendAsync(requestMessage); var content = await response.Content.ReadAsStringAsync(); if (response.StatusCode == HttpStatusCode.OK) { return Ok(content); } return BadRequest(); } catch (Exception e) { return StatusCode(502); } } }