使用asp.net 5 TestServer模拟外部Api调用

时间:2015-04-14 07:12:51

标签: .net unit-testing asp.net-core

我正在尝试使用TestServer来测试我的中间件。 在中间件的某个地方,我的代码通过HttpClient调用api。我想通过使用第二个TestServer来模拟这个但是想知道这是否可行。我已经尝试了,但是我有错误:"尝试连接...但服务器主动拒绝了它。"

以下是代码的外观:

  [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的代码中,我正在做一个

 HttpClient client = new HttpClient() { BaseAddress = "http://fakeUrl.com"};
 var resp = client.GetAsync("/path/to/api");

url:http://fakeUrl.com将被假冒服务器嘲笑。但事实上,http://fakeUrl的真实呼叫是通过网络发出的,但是我希望它能够点击假的服务器,以便我可以模拟那个api。

想象一下,假冒服务器会嘲笑google calendar api。

更新:使用fakeServer 事实上,fakeServer会听取这个网址:&#34; http://fakeUrl.com&#34;当收到路线&#34; / path / to / api&#34;例如,它会返回一个json对象。我想要的是,我的fakeServer返回一个模拟对象。提醒一下,&#34; http://fakeUrl.com/path/to/api&#34;将在我的代码中使用HttpClient对象调用。

1 个答案:

答案 0 :(得分:1)

我找到了一个解决方案,但是使用visual studio 2015 CTP6测试有时会通过,有时候不会......它似乎是一个Xunit问题,因为当我调试时,一切都很好......但是那个&#39这不是问题

链接到完整代码:github repo

这是我要测试的中间件:

      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>();
              }
          }
      }

请注意, Invoke 方法正在获取一个IClientProvider(通过DI),该IClientProvider将根据某些字符串返回不同的HttpClient对象(这里只是为了演示目的。)字符串可以是providerName .... 然后我们使用这些客户端调用外部api。 我想要模拟

这是 IClientProvider 界面:

    using System.Net.Http;

    namespace Multi.Web.Api
    {
        public interface IClientProvider
        {
            HttpClient GetClientFor(string providerName);
        }
    }

然后,我创建了一个中间件(测试中间件)来模拟来自SUT的请求(在上面)

    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>();
            }
        }

    }

这里我模拟来自两个不同主机的请求并听取不同的路径。我也可以做两个中间件,每个主机一个

接下来,我创建了一个使用此FakeExternalApi的 TestClientHelper

    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();
            }
        }
    }

它基本上做的是为我们要求的服务器返回正确的客户端。

现在我可以创建我的测试方法:

      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目标返回给真正的主机。 (工厂)

我不知道它是否是最佳解决方案,但它符合我的需求......仍有Xunit.net的问题需要解决......