控制器
[Route("api/order")] [ApiController] public class OrderController : ControllerBase { readonly HttpClient messageClient; public OrderController(IHttpClientFactory clientFactory) { // 创建消息服务所使用的客户端,名称与配置所使用的名称一致 // 实际项目中千万不要写上哦~ messageClient = clientFactory.CreateClient("MESSAGESERVICE"); } [HttpPost] public async Task<ResponseMessage> SaveOrder([FromBody]Order order) { // 保存订单,省略了.... // 调用消息服务接口 ResponseMessage response = await messageClient.PostAsync<ResponseMessage>( "/message/send", new SendMessageRequest() { MessageId = Guid.NewGuid().ToString("N").ToLower(), Message = "订单已提交", UserIds = new List<int>() { 1,2,3} }); // 根据消息服务返回应答继续处理,省略了... return response; } }启动,然后通过Api测试工具(如Postman)向/api/order POST请求,接口将返回以下应答:
{ "code": "0", "message": null, "isSuccess": true }如上,通过Http请求模拟,我们实现了订单服务对消息服务的依赖。
二、在单元测试中使用单元测试中,针对模拟应答的配置是一样的,我们可以通过测试用例模拟各种不同的应答,包括异常,来对执行路径进行测试。
[Fact] public async Task Test1() { IServiceCollection services = new ServiceCollection() .AddExtensions(); services.AddHttpClient("TESTCLIENT") .AddMockHttpMessageHandler() // 请求/test/exception将触发异常 .AddMock("/test/exception", HttpMethod.Get, new Exception("")) // 针对 /test/404 返回404应答 .AddMock("/test/404", HttpMethod.Get, HttpStatusCode.NotFound) // 返回指定类型 .AddMock<int>("/test/obj", HttpMethod.Get, 100) // 自定义条件及应答 .AddMock(request => { if (request.Headers.Contains("hello")) { return true; } return false; }, async (request, response) => { // 如果是调用第三方服务,你可以在这里检查request发出的请求内容是否正确 // 自定义应答内容 await response.WriteObjectAsync(new { test = "Hello World" }); }) // 针对所有请求返回字符串Hello .AddMock("*", HttpMethod.Get, "Hello"); IServiceProvider provider = services.BuildServiceProvider(); IHttpClientFactory clientFactory = provider.GetRequiredService<IHttpClientFactory>(); HttpClient client = clientFactory.CreateClient("TESTCLIENT"); client.BaseAddress = new Uri("http://localhost"); HttpResponseMessage resposne = await client.GetAsync("/test/404"); Assert.Equal(HttpStatusCode.NotFound, resposne.StatusCode); } 三、示例详细示例请参考GitHub
Xfrogcn.AspNetCore.Extensions地址:GitHub Gitee