测试集成 .Net Core 与 TestServer return 404 未找到?

Test integration .Net Core with TestServer return 404 not found?

我正在尝试创建一个集成测试项目,用于测试我的网站 api .Net Core 以及此处的 Microsoft 示例最佳实践 https://docs.microsoft.com/en-us/aspnet/core/testing/integration-testing 但我不知道为什么,我总是收到错误消息 [404 not found],HttpClient 找不到 'testServer' 。如果我从 iisexpress 尝试调试模式,我确定我的 'route' 是正确的 ["api/Registration/" + guid] 。效果很好

如果有人有解决办法,将不胜感激。谢谢

这是我在集成测试项目中使用的代码:

RegistrationIntegrationTest.cs:

[TestClass]
public class RegistrationIntegrationTest
{
    private static TestServer server;
    private static HttpClient client;

    [ClassInitialize]
    public static void ClassInitialize(TestContext context)
    {
        var basePath = PlatformServices.Default.Application.ApplicationBasePath;
        var projectPath = Path.GetFullPath(Path.Combine(basePath, "../../../../Registration"));

        var builder = new WebHostBuilder()
            .UseContentRoot(projectPath)
            .UseEnvironment(EnvironmentName.Development)
            .UseStartup<Startup>();

        server = new TestServer(builder);
        client = server.CreateClient();
    }

    private async Task<string> GetRegistrationResponse(string guid)
    {
        var request = "api/Registration/" + guid;

        var response = await client.GetAsync(request);
        response.EnsureSuccessStatusCode();

        return await response.Content.ReadAsStringAsync();
    }

    [TestMethod]
    public async Task GetRegistration()
    {
        // Act
        var responseString = await GetRegistrationResponse("A5A3CBFD-8B61-E711-80E2-00505693113A");
        // Assert
        Assert.Equals("test",
            responseString);
    }
}

这是我的启动 Class 来自我的集成测试项目:

Startup.cs

public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            //.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            //.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();

    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
        services.AddCors();
        services.AddAntiforgery();
        services.AddSingleton<IControllerActivator>(new SimpleInjectorControllerActivator(this.Container));
        services.Configure<MyAppSettings>(Configuration);
        services.UseSimpleInjectorAspNetRequestScoping(this.Container);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));

        if (env.IsDevelopment())
        {
            loggerFactory.AddDebug();
            app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
        }
        else if (env.IsStaging())
        {
            app.UseCors(builder => builder.WithOrigins("https://apitest.swisscaution.ch"));
        }
        else if (env.IsProduction())
        {
            app.UseCors(builder => builder.WithOrigins("https://internalapi.swisscaution.ch"));
        }
        else
        {
            throw new InvalidOperationException("Bad application environement.");
        }

        app.UseMvc();

        this.InitializeContainer(app);
    }

这是我的解决方案架构的照片 Visual Studio, 如您所见,集成测试项目与我名为 'registration' 的 Web api 项目是分开的

我得到的异常:

终于找到问题所在了。 是因为我的 [ 集成测试项目 ] 是针对 .Net Core 版本的,我试图用 .Net Framework 4.5.6 版本测试和托管一个项目。 我在网上找到解决方案,我需要修改csproj文件并在"PropertyGroup"部分添加这3个配置。

<PropertyGroup>
    <TargetFramework>net461</TargetFramework>
    <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
  </PropertyGroup>

这是我找到的url:http://quabr.com/44027215/system-net-http-httpclient-microsoft-aspnetcore-testhost-testserver-createclient