使用asp.net 5 TESTSERVER嘲笑外部API调用 [英] Using asp.net 5 TestServer to Mock an external Api call
问题描述
I am trying to use TestServer to test my middleware. Somewhere in the middleware, my code is calling an api through HttpClient. I would like to mock this by using a second TestServer but wonder if this is possible. I already tried, but I have the error : "Trying to connect ... but the server actively refused it."
在这里是怎么了code可能是这样的:
here is how the code could look like :
[Fact]
public async Task Should_give_200_Response()
{
var server = TestServer.Create((app) =>
{
app.UseMiddleware<DummyMiddleware>();
});
var fakeServer = TestServer.Create((app) =>
{
app.UseMiddleware<FakeMiddleware>();
});
using(server)
{
using(fakeServer)
{
var response = await server.CreateClient().GetAsync("/somePath");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
某处在DummyMiddleware的code,我做了
Somewhere in the code of DummyMiddleware, I am doing an
HttpClient client = new HttpClient() { BaseAddress = "http://fakeUrl.com"};
var resp = client.GetAsync("/path/to/api");
链接: http://fakeUrl.com 将由fakeServer被嘲笑。但事实上,以 HTTP真正的呼叫:// fakeUrl 发在网络上,但我想它打fakeserver使我可以嘲笑的API。
the url : http://fakeUrl.com would be mocked by the fakeServer. but in fact a real call to http://fakeUrl is issued over the network, but I would like it to hit the fakeserver so that I could mock that api.
想象fakeserver会嘲笑谷歌日历的API实例。
Imagine that the fakeserver would mock google calendar api for instance.
更新:使用fakeServer的 事实上,fakeServer会听这个网址: http://fakeUrl.com ,当接收这条路/路径/到/ API,它会返回一个JSON对象实例。我想,是我fakeServer要返回一个嘲笑的对象。作为提醒, http://fakeUrl.com/path/to/api 将在我的code与HttpClient的对象调用的某个地方。
Update : Use of fakeServer In fact the fakeServer would listen to this url : "http://fakeUrl.com" and when receive the route "/path/to/api" it would return a json object for instance. What I would like to, is my fakeServer to be returned a mocked object. as a reminder, "http://fakeUrl.com/path/to/api" would be called somewhere in my code with an HttpClient object.
推荐答案
我找到了一个解决方案,但与Visual Studio 2015年CTP6测试有时路过,有时不...看来这是一个xUnit的问题,因为当我调试,一切都很好......但是这不是这里的问题
I found a solution, but with visual studio 2015 CTP6 test are sometimes passing, sometimes not... it seems it's an Xunit problem, because when I debug, everything is fine... but that's not the problem here
链接到code: GitHub库
下面是中间件我想测试一下:
here is the middleware I want to test :
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace Multi.Web.Api
{
public class MultiMiddleware
{
private readonly RequestDelegate next;
public MultiMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context, IClientProvider provider)
{
HttpClient calendarClient = null;
HttpClient CalcClient = null;
try
{
//
//get the respective client
//
calendarClient = provider.GetClientFor("calendar");
CalcClient = provider.GetClientFor("calc");
//
//call the calendar api
//
var calendarResponse = "";
if (context.Request.Path.Value == "/today")
{
calendarResponse = await calendarClient.GetStringAsync("http://www.calendarApi.io/today");
}
else if (context.Request.Path.Value == "/yesterday")
{
calendarResponse = await calendarClient.GetStringAsync("http://www.calendarApi.io/yesterday");
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
//does not process further
return;
}
//
//call another api
//
var calcResponse = await CalcClient.GetStringAsync("http://www.calcApi.io/count");
//
// write the final response
//
await context.Response.WriteAsync(calendarResponse + " count is " + calcResponse);
await next(context);
}
finally
{
if (calendarClient != null)
{
calendarClient.Dispose();
}
if (CalcClient != null)
{
CalcClient.Dispose();
}
}
}
}
public static class MultiMiddlewareExtensions
{
public static IApplicationBuilder UseMulti(this IApplicationBuilder app)
{
return app.UseMiddleware<MultiMiddleware>();
}
}
}
请注意,在调用方法得到一个IClientProvider(通过DI),将根据一些字符串返回不同的HttpClient对象(这里只是为了演示的目的。)该字符串可能是一个的providerName .... 然后我们使用这些客户端调用外部的API。 这是thtis,我想嘲弄
Notice that the Invoke method is getting a IClientProvider (through DI) that will return different HttpClient object based on some string (here it's just for the purpose of demo.) the string could be a providerName.... Then we use these clients to call external apis. It's thtis that I want to Mock
这里是 IClientProvider 接口:
using System.Net.Http;
namespace Multi.Web.Api
{
public interface IClientProvider
{
HttpClient GetClientFor(string providerName);
}
}
然后,我创建了一个中间件(测试中间件)嘲笑请求从SUT未来(即在于此以上)
Then, I've created a middleware (test middleware) to mock the request coming from the SUT (that is here above)
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using System;
using System.Threading.Tasks;
namespace Multi.Web.Api.Test.FakeApi
{
public class FakeExternalApi
{
private readonly RequestDelegate next;
public FakeExternalApi(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
//Mocking the calcapi
if (context.Request.Host.Value.Equals("www.calcapi.io"))
{
if (context.Request.Path.Value == "/count")
{
await context.Response.WriteAsync("1");
}
}
//Mocking the calendarapi
else if (context.Request.Host.Value.Equals("www.calendarapi.io"))
{
if (context.Request.Path.Value == "/today")
{
await context.Response.WriteAsync("2015-04-15");
}
else if (context.Request.Path.Value == "/yesterday")
{
await context.Response.WriteAsync("2015-04-14");
}
else if (context.Request.Path.Value == "/tomorow")
{
await context.Response.WriteAsync("2015-04-16");
}
}
else
{
throw new Exception("undefined host : " + context.Request.Host.Value);
}
await next(context);
}
}
public static class FakeExternalApiExtensions
{
public static IApplicationBuilder UseFakeExternalApi(this IApplicationBuilder app)
{
return app.UseMiddleware<FakeExternalApi>();
}
}
}
在这里,我嘲笑从两个不同的主机请求到来,聆听不同的路径。我可以做两中间件还为每个主机
here I mock request coming from a two different host and listen to different path. I could do two middleware also, one for each host
接下来,我创建了一个 TestClientHelper 使用该FakeExternalApi
next, I created a TestClientHelper that uses this FakeExternalApi
using Microsoft.AspNet.TestHost;
using Multi.Web.Api.Test.FakeApi;
using System;
using System.Net.Http;
namespace Multi.Web.Api
{
public class TestClientProvider : IClientProvider, IDisposable
{
TestServer _fakeCalendarServer;
TestServer _fakeCalcServer;
public TestClientProvider()
{
_fakeCalendarServer = TestServer.Create(app =>
{
app.UseFakeExternalApi();
});
_fakeCalcServer = TestServer.Create(app =>
{
app.UseFakeExternalApi();
});
}
public HttpClient GetClientFor(string providerName)
{
if (providerName == "calendar")
{
return _fakeCalendarServer.CreateClient();
}
else if (providerName == "calc")
{
return _fakeCalcServer.CreateClient();
}
else
{
throw new Exception("Unsupported external api");
}
}
public void Dispose()
{
_fakeCalendarServer.Dispose();
_fakeCalcServer.Dispose();
}
}
}
它通常做的是返回正确的客户端,我们要求的服务器。
What it basically does is returning the correct client for the server we asked for.
现在我可以创造我的测试方法:
Now I can create my Tests Methods :
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNet.TestHost;
using Microsoft.Framework.DependencyInjection;
using Shouldly;
using Xunit;
using Microsoft.AspNet.Builder;
using System.Net.Http;
namespace Multi.Web.Api
{
public class TestServerHelper : IDisposable
{
public TestServerHelper()
{
ClientProvider = new TestClientProvider();
ApiServer = TestServer.Create((app) =>
{
app.UseServices(services =>
{
services.AddSingleton<IClientProvider>(s => ClientProvider);
});
app.UseMulti();
});
}
public TestClientProvider ClientProvider { get; private set; }
public TestServer ApiServer { get; private set; }
public void Dispose()
{
ApiServer.Dispose();
ClientProvider.Dispose();
}
}
public class MultiMiddlewareTest : IClassFixture<TestServerHelper>
{
TestServerHelper _testServerHelper;
public MultiMiddlewareTest(TestServerHelper testServerHelper)
{
_testServerHelper = testServerHelper;
}
[Fact]
public async Task ShouldReturnToday()
{
using (HttpClient client = _testServerHelper.ApiServer.CreateClient())
{
var response = await client.GetAsync("http://localhost/today");
response.StatusCode.ShouldBe(HttpStatusCode.OK);
String content = await response.Content.ReadAsStringAsync();
Assert.Equal(content, "2015-04-15 count is 1");
}
}
[Fact]
public async Task ShouldReturnYesterday()
{
using (HttpClient client = _testServerHelper.ApiServer.CreateClient())
{
var response = await client.GetAsync("http://localhost/yesterday");
response.StatusCode.ShouldBe(HttpStatusCode.OK);
String content = await response.Content.ReadAsStringAsync();
Assert.Equal(content, "2015-04-14 count is 1");
}
}
[Fact]
public async Task ShouldReturn404()
{
using (HttpClient client = _testServerHelper.ApiServer.CreateClient())
{
var response = await client.GetAsync("http://localhost/someOtherDay");
response.StatusCode.ShouldBe(HttpStatusCode.NotFound);
}
}
}
}
在 TestServHelper 包装了API和 ClientProvider 在这里是一个模拟实现,但在生产这将是一个真正的ClientProvider的实施,将返回HttpClient的目标到真正的主机。 (一厂)
The TestServHelper wraps up the Api and the ClientProvider which here is a mock implementation, but in production it will be a real ClientProvider implementation that will return HttpClient target to the real Hosts. (a factory)
我不知道这是否是最佳的解决方案,但它适合我的需要?还是有问题Xunit.net解决...
I don't know if it's the best solution, but it suits my needs... Still have the problem with Xunit.net to solve...
这篇关于使用asp.net 5 TESTSERVER嘲笑外部API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!