2

我创建了 ASP.NET Web API 的自托管实现,并希望它在 SpecFlow 测试中运行。

因此,在我的规格中,我有一步启动 selfhostserver,如下所示:

var config = new HttpSelfHostConfiguration("http://localhost:9000");    
var server = new HttpSelfHostServer(config);

 _apiApplication.Start(); //IoC, route-configs etc.

server.OpenAsync().Wait();

var httpClient = new HttpClient();
var response = httpClient.GetAsync(fetchUrl).Result;

GetAsync 调用发生的异常:

Exception : System.AggregateException: One or more errors occurred. 
---> System.Net.Http.HttpRequestException: An error occurred while sending the request. 
---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. 
---> System.IO.IOException: Unable to read data from the transport connection

在规范完成之前,测试运行似乎阻止了对自托管 API 的任何调用。调试时,我可以调用 url - 但它会挂起,直到测试运行完成。完成后,它给出了很好的响应。

我还创建了一个控制台应用程序,它可以完美地运行此代码,并给出预期的结果。

任何拥有通过 HttpSelfHostServer 进行测试的 SpecFlow 测试套件的人,或者知道如何让自托管 WebApi 在 SpecFlow 套件中工作?

4

3 回答 3

0

自从被问到这个问题以来,我一直在看这个问题,因为我们遇到了完全相同的问题。

目前,我们正在调用 IIS express 来托管我们的 WebAPI 服务,在 specFlow 运行开始时启动它们,并在最后处理它们,使用 IIS 自动化 nuget 包https://github.com/ElemarJR/IISExpress.Automation

我们也遇到了 MS 测试运行器的问题,但使用 ReSharper,它们目前似乎都运行正确。

如果其他人有任何贡献,我也很感兴趣

于 2013-08-16T11:46:09.503 回答
0

我已经设法为 WCF 服务而不是 Web 应用程序执行此操作,但理论上它应该是相同的。

一个大问题是释放服务器上的端口,因此我为每次运行分配不同的端口,如下

private static int FreeTcpPort()
    {
        var l = new TcpListener(IPAddress.Loopback, 0);
        l.Start();
        int port = ((IPEndPoint)l.LocalEndpoint).Port;
        l.Stop();
        return port;
    }


    [Given(@"a WCF Endpoint")]
    public void GivenAWCFEndpoint()
    {
        //The client 
        RemoteServerController.DefaultPort = FreeTcpPort();

        //The server
        var wcfListener = new ListenerServiceWCF
            {
                BindingMode = BindingMode.TCP,
                Uri = new Uri(string.Format("net.tcp://localhost:{0}",
                     RemoteServerController.DefaultPort))
            };
        //The wrapped host is quite a bit of generic code in our common libraries
        WrappedHostServices.Add(wcfListener);
        WrappedHostServices.Start();
    }

即使这样,我仍然偶尔会遇到测试失败,因此如果您可以减少运行代码的基础设施数量,那么我建议您在没有它的情况下运行大部分测试,并且只运行几个以确保它正常工作。

于 2013-08-13T15:25:40.597 回答
0

我相信您忘记了 ReadAsync() 上的 Wait() 语句。试试下面的:

    var config = new HttpSelfHostConfiguration("http://localhost:9000");    
    var server = new HttpSelfHostServer(config);

     _apiApplication.Start(); //IoC, route-configs etc.

    server.OpenAsync().Wait();

    var httpClient = new HttpClient();
    var requestTask = httpClient.GetAsync(fetchUrl);
    requestTask.Wait();
    var response = requestTask.Result;

这应该可以防止您的代码立即退出,这可能就是您收到异常的原因。

于 2014-04-07T19:43:30.320 回答