如何在我的测试中使用NinjectSelfHostBootstrapper并且有多个测试通过?

时间:2015-03-30 23:26:18

标签: c# asp.net-web-api ninject

这是我的NUnit测试代码(简化以隔离问题):

public class MyController : ApiController
{
    [HttpGet]
    [Route("api/route")]
    public string Route1()
    {
        return "route";
    }
}

[TestFixture]
public class MyTestFixture
{
    private NinjectSelfHostBootstrapper _bootstrapper;

    [SetUp]
    public void SetUp()
    {
        var config = new HttpSelfHostConfiguration("http://localhost:8767");
        config.MapHttpAttributeRoutes();

        var kernel = new StandardKernel();
        this._bootstrapper = new NinjectSelfHostBootstrapper(() => kernel, config);
        this._bootstrapper.Start();
    }

    [TearDown]
    public void TearDown()
    {
        if (this._bootstrapper != null)
        {
            this._bootstrapper.Dispose();
        }
    }

    [Test]
    public void MyTest1()
    {
        using (var client = new HttpClient())
        {
            var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:8767/api/route");
            var response = client.SendAsync(request).Result;
            var content = response.Content.ReadAsStringAsync().Result;

            Assert.That(content, Is.EqualTo("\"route\""));
        }
    }

    [Test]
    public void MyTest2()
    {
        using (var client = new HttpClient())
        {
            var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:8767/api/route");
            var response = client.SendAsync(request).Result;
            var content = response.Content.ReadAsStringAsync().Result;

            Assert.That(content, Is.EqualTo("\"route\""));
        }
    }
}

当我使用默认的NinjectSelfHostBootstrapper运行时,第一个测试通过正常,但第二个测试抛出异常,说:

  

URI'http://localhost:8767/'已经存在注册。

当我检查这两个文件的代码时:

https://github.com/ninject/Ninject.Web.WebApi/blob/master/src/Ninject.Web.WebApi.Selfhost/NinjectWebApiSelfHost.cs

https://github.com/ninject/Ninject.Web.Common/blob/master/src/Ninject.Web.Common.SelfHost/NinjectSelfHostBootstrapper.cs

我明白为什么 - 在后者中创建HttpSelfHostServer并在服务器上调用OpenAsync(),但在服务器上未调用CloseAsync() - 是这个一个错误或我做错了什么?如何让NinjectSelfHostBootstrapper使用后续调用的测试?

0 个答案:

没有答案