TestServer返回未找到的404

时间:2019-08-15 04:12:12

标签: c# asp.net-core nunit integration-testing asp.net-core-webapi

我正在为我的Web api项目使用aspnetcore 3.0预览版7。目前,我正在实施集成测试。 (为使测试更容易,我在控制器上注释了Authorize属性。)

服务器响应“找不到404”。 我对启动中不再有“ usemvc”感到困惑-我现在应该在设置测试服务器上做些不同的事情吗? 还是有人知道导致404的原因? (用于3.0集成测试的MS文档尚未更新)。 我也尝试使用预览版8,但问题相同。

测试类:

   [OneTimeTearDown]
    public virtual void Cleanup()
    {
        _unAuthenticatedServer.Dispose();
    }

    [OneTimeSetUp]
    public virtual void Initialize()
    {
        _unAuthenticatedServer = CreateServer(null);
    }

    protected TestServer CreateServer(
        string currentDirectory = null)
    {
        IWebHostBuilder webHostBuilder = WebHost.CreateDefaultBuilder();

        webHostBuilder.UseContentRoot(currentDirectory == null
            ? Directory.GetCurrentDirectory()
            : Directory.GetCurrentDirectory() + $"\\{currentDirectory}");


        webHostBuilder.UseStartup<TestStartup>();
        webHostBuilder.UseEnvironment("Test");

        webHostBuilder.ConfigureAppConfiguration((_, config) => config.AddJsonFile("appsettings.Test.json"));

        return new TestServer(webHostBuilder);
    }

    [Test, Order(1)]
    public async Task Should_Get_Games_Return_StatusCode_Ok()
    {
        //Arrange
        IList<GameDto> expectedDtos = GameDtoTestData.Games;

        //Act
        HttpResponseMessage responseMessage = await _unAuthenticatedServer
            .CreateClient()
            .GetAsync("api/games");

        //Assert
        responseMessage.StatusCode.Should().Be(HttpStatusCode.OK); // but is: 404 NotFound

        var responseString = await responseMessage.Content.ReadAsStringAsync();
        IEnumerable<GameDto> result = JsonConvert.DeserializeObject<IEnumerable<GameDto>>(responseString);

        result.Should().BeEquivalentTo(expectedDtos);
    }

控制器:

[Route("api/[controller]")]
[ApiController]
public class GamesController : ControllerBase
{
    private readonly IGameService _gameService;

    public GamesController(IGameService gameService)
    {
        _gameService = gameService;
    }

    [HttpGet]
    public async Task<ActionResult<IEnumerable<GameDto>>> Get()
    {
        return Ok(await _gameService.GetAsync());
    }
}

已安装的Nuget软件包测试项目:

 <ItemGroup>
    <PackageReference Include="FluentAssertions" Version="5.8.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="3.0.0-preview7.19365.7" />
    <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="3.0.0-preview7.19365.7" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="2.2.6" />
    <PackageReference Include="nunit" Version="3.12.0" />
    <PackageReference Include="NUnit3TestAdapter" Version="3.14.0" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.2.0" />
  </ItemGroup>

已安装的Nuget软件包api项目:

  <ItemGroup>
    <PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="7.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.AzureADB2C.UI" Version="3.0.0-preview6.19307.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.6" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.2.6" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.2.6" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.6">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>

1 个答案:

答案 0 :(得分:7)

对我有用的是将包含Startup类的程序集注册为Mvc应用程序零件。

在您的启动类中,修改IServiceProvider ConfigureServices(IServiceCollection services),使其包含以下代码:

services
  .AddMvc(...)
  .AddApplicationPart(typeof(Startup).Assembly)

您似乎需要将包含Startup类的程序集注册为Startup类本身的应用程序部分,这似乎有些奇怪。但是这种方法确实对我有用。