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

时间:2017-07-07 05:05:33

标签: .net unit-testing asp.net-core integration-testing httpclient

我正在尝试创建一个Integration Test项目,用于测试我的web api .Net Core以及此处的Microsoft示例最佳实践https://docs.microsoft.com/en-us/aspnet/core/testing/integration-testing 但我不知道为什么,我总是收到错误消息[404 not found],HttpClient无法找到' testServer' 。而且我确定我的路线'是对的[" api / Registration /" + guid],如果我尝试从iisexpress调试模式。它的工作很棒

如果有人有想法修复它,将非常感激。感谢

以下是我在Integration Test项目中使用的代码:

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);
    }
}

这是我的Integration Test项目中的启动类:

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的架构照片, 正如您所看到的,集成测试项目与我的名为“注册”的web api项目是分开的。 enter image description here

我得到的例外情况: enter image description here

1 个答案:

答案 0 :(得分:1)

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

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

以下是我找到的网址:http://quabr.com/44027215/system-net-http-httpclient-microsoft-aspnetcore-testhost-testserver-createclient