[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
以上就是ASP.NET Core扩展库之Http请求模拟功能的使用的详细内容,更多关于ASP.NET Core Http请求模拟功能的使用的资料请关注脚本之家其它相关文章!
您可能感兴趣的文章: