如何将TestServerFixture注入我的Test类?

时间:2018-06-22 12:27:53

标签: c# integration-testing xunit

我试图将 TestServer 注入XUnit中的Test类,但出现此错误:

<div class="looong">
  Some Text, Big div
</div>
<svg id="overlay">
	<defs>
		<mask id="overlay-mask">
			<rect x="0" y="0" width="100%" height="100%" fill="white"></rect>
			<rect id="cutout" x="100" y="200" width="100" height="50" fill="black"></rect>
		</mask>
	</defs>
	<rect x="0" y="0" width="100%" height="100%" fill="black" fill-opacity="0.6" mask="url(#overlay-mask)" ></rect>
</svg>

我的 TestServerFixture。类如下:

Test Name:  NaviqTests.UnitControllerTest.AddUnit_InvalidModel_ShouldReturnBadRequest
Test FullName:  NaviqTests.UnitControllerTest.AddUnit_InvalidModel_ShouldReturnBadRequest
Test Source:    C:\Naviq\api\NaviqTests\UnitControllerTest.cs : line 15
Test Outcome:   Failed
Test Duration:  0:00:00.001

Result StackTrace:  
----- Inner Stack Trace #1 (System.MissingMethodException) -----
   at NaviqTests.TestServerFixture..ctor()
----- Inner Stack Trace #2 (Xunit.Sdk.TestClassException) -----
Result Message: 
System.AggregateException : One or more errors occurred. (Method not found: 'Void Microsoft.AspNetCore.Hosting.Server.IServer.Start(Microsoft.AspNetCore.Hosting.Server.IHttpApplication`1<!!0>)'.) (The following constructor parameters did not have matching fixture data: TestServerFixture fixture)
---- System.MissingMethodException : Method not found: 'Void Microsoft.AspNetCore.Hosting.Server.IServer.Start(Microsoft.AspNetCore.Hosting.Server.IHttpApplication`1<!!0>)'.
---- The following constructor parameters did not have matching fixture data: TestServerFixture fixture

我的测试班:

  public class TestServerFixture : IDisposable {
    private readonly TestServer _testServer;
    public HttpClient Client { get; }

    public TestServerFixture() {
      var builder = new WebHostBuilder()
        .UseEnvironment("Development")
        .UseStartup<Startup>(); // Uses Start up class from your API Host project to configure the test server

      _testServer = new TestServer(builder);
      Client = _testServer.CreateClient();
    }

    public void Dispose() {
      Client.Dispose();
      _testServer.Dispose();
    }
  }

我知道我可以在TestServer初始化中使用它,但是看起来会很乱。

  public class UnitControllerTest : IClassFixture<TestServerFixture> {

    private readonly TestServerFixture _fixture;

    public UnitControllerTest(TestServerFixture fixture) {
      _fixture = fixture;
    }

    [Fact]
    public async Task AddUnit_InvalidModel_ShouldReturnBadRequest() {
      var response = await _fixture.Client.GetAsync("api/unit/1");
      Assert.Equal(HttpStatusCode.OK ,response.StatusCode);
    }
  }

还有更好的方法吗?还是应该留在using (var server = new TestServer(hostBuilder)) 上?

0 个答案:

没有答案