2014-01-29 31 views
1

由于以前的测试未关闭HttpSelfHostServer会话,因此我们正在进行单元测试失败。当使用HttpSelfHostServer时,“URI的注册已存在”

所以我们第二次尝试打开到服务器的连接,我们得到这个消息:

System.InvalidOperationException : A registration already exists for URI 'http://localhost:1337/'. 

这个测试强制问题(作为一个例子):

[TestFixture] 
    public class DuplicatHostIssue 
    { 
    public HttpSelfHostServer _server; 

    [Test] 
    public void please_work() 
    { 
     var config = new HttpSelfHostConfiguration("http://localhost:1337/"); 
     _server = new HttpSelfHostServer(config); 
     _server.OpenAsync().Wait(); 

     config = new HttpSelfHostConfiguration("http://localhost:1337/"); 
     _server = new HttpSelfHostServer(config); 
     _server.OpenAsync().Wait(); 
    } 
} 

所以newing了服务器剂量的新实例似乎杀死了以前的会话。任何想法如何强制前一届会议的处置?

完全例外,如果有帮助?

 System.AggregateException : One or more errors occurred. ----> System.InvalidOperationException : A registration already exists for URI 'http://localhost:1337/'.  
    at 

System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken) at System.Threading.Tasks.Task.Wait()  
at ANW.API.Tests.Acceptance.DuplicatHostIssue.please_work() in DuplicatHostIssue.cs: line 32 
    --InvalidOperationException  
at System.Runtime.AsyncResult.End(IAsyncResult result)  
at System.ServiceModel.Channels.CommunicationObject.EndOpen(IAsyncResult result) 
at System.Web.Http.SelfHost.HttpSelfHostServer.OpenListenerComplete(IAsyncResult result) 
+0

您可以避免此问题的一种方法是使用内存中的主机来执行您的单元测试。它会让你的测试运行得更快! –

回答

1

你可能想要写一个Dispose方法如下图所示,并适当地调用它来避免这个问题

private static void HttpSelfHostServerDispose() 
{ 
    if (server != null) 
    { 
     _server.CloseAsync().Wait(); 
     _server.Dispose(); 
     _server = null; 
    } 
} 

这将清除URI寄存器。