【问题标题】:How to run XUnit test on both self-host & production webapi service?如何在自托管和生产 webapi 服务上运行 XUnit 测试?
【发布时间】:2013-05-22 14:28:44
【问题描述】:

我想为我的 ASP.NET WebApi 服务编写一个测试,并针对自托管服务和实时 Web 托管服务运行它。我想这可以用一个测试夹具来完成,但我不知道如何设置它。有谁知道使用可配置测试夹具的示例,以便您可以将参数传递给 Xunit 以选择自托管夹具或网络托管夹具?

【问题讨论】:

    标签: testing asp.net-web-api xunit fixture self-hosting


    【解决方案1】:

    这是最新的 xUnit 2.0 beta 的工作方式。

    创建一个夹具:

    public class SelfHostFixture : IDisposable {
        public static string HostBaseAddress { get; private set; }
        HttpSelfHostServer server;
        HttpSelfHostConfiguration config;
    
        static SelfHostFixture() {
            HostBaseAddress = ConfigurationManager.AppSettings["HostBaseAddress"]; // HttpClient in your tests will need to use same base address
            if (!HostBaseAddress.EndsWith("/"))
                HostBaseAddress += "/";
        }
    
        public SelfHostFixture() {
            if (/*your condition to check if running against live*/) {
                config = new HttpSelfHostConfiguration(HostBaseAddress);
                WebApiConfig.Register(config); // init your web api application
                var server = new HttpSelfHostServer(config);
                server.OpenAsync().Wait();
            }
        }
    
        public void Dispose() {
            if (server != null) {
                server.CloseAsync().Wait();
                server.Dispose();
                server = null;
    
                config.Dispose();
                config = null;
            }
        }
    }
    

    然后定义一个将使用该夹具的集合。集合是 xUnit 2 中对测试进行分组的新概念。

    [CollectionDefinition("SelfHostCollection")]
    public class SelfHostCollection : ICollectionFixture<SelfHostFixture> {}
    

    它只是一个标记,所以没有实现。 现在,将依赖于您的主机的测试标记在该集合中:

    [Collection("SelfHostCollection")]
    public class MyController1Test {}
    
    [Collection("SelfHostCollection")]
    public class MyController4Test {}
    

    MyController1TestMyController4Test 中运行任何测试时,运行程序将创建一个fixture 实例,确保每个集合只启动一次服务器。

    【讨论】:

      【解决方案2】:

      我建议使用 In-Memory Server 来测试您的控制器,因此您无需在单元测试中启动自主机。

      http://blogs.msdn.com/b/youssefm/archive/2013/01/28/writing-tests-for-an-asp-net-webapi-service.aspx

      【讨论】:

      • 仅供参考...在进行内存测试时,我们需要确保请求和响应通过格式化程序的序列化/反序列化过程来捕获任何问题...这里有一些信息我很老的帖子:blogs.msdn.com/b/kiranchalla/archive/2012/05/06/… ...考虑到这一点,我认为进行自托管测试是一个更好的选择...
      猜你喜欢
      • 2018-11-16
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      • 1970-01-01
      • 1970-01-01
      • 2011-02-11
      • 2014-05-07
      相关资源
      最近更新 更多