集成测试期间首次运行时出现错误的请求错误

时间:2018-07-30 05:19:23

标签: entity-framework-core integration-testing asp.net-core-2.0 xunit

我有一个Web api,identityserver4和一个xUnit集成测试项目。在网络api中,我有一个用于测试目的的简单控制器,该控制器返回具有[Authorize]属性的字符串。

TestFixture类中,我有类似的构造函数

public TestFixture()
{
    IWebHostBuilder identityServerHostBuilder = GetWebHostBuilder<IdentityServer4.Startup>();
    this.identityTestServer = new TestServer(identityServerHostBuilder);
    this.identityTestServer.BaseAddress = new Uri("xxxxx:xxxx");
    this.identityServerClient = this.identityTestServer.CreateClient();

    var identityServerServiceProvider = this.identityTestServer.Host.Services.GetRequiredService<IServiceProvider>();
    // DbInitializer class creates the database, applies migrations and seed data.
    Task.Run(() => DbInitializer.Seed(identityServerServiceProvider)).Wait();

    IWebHostBuilder apiServerHostBuilder = GetWebHostBuilder<API.Startup>();
    this.apiTestServer = new TestServer(apiServerHostBuilder);
    this.apiTestServer.BaseAddress = new Uri("xxxxx:xxxx");
    this.AuthorizedClient = this.apiTestServer.CreateClient();
    Task.Run(async () => this.AuthorizedClient.SetBearerToken(await this.GetBearerToken())).Wait();
}

GetBearerToken()向IdentityServer4发出POST请求以获取Bearer令牌:

private async Task<string> GetBearerToken()
{
    var uri = "connect/token";
    var form = new Dictionary<string, string>
    {
       { "grant_type", "password" },
       { "username", "xxx@xxx.xxx" },
       { "password", "xxxxx" },
       { "client_id", "xxxxx" }
    };

    var response = await this.identityServerClient.PostAsync(uri, new FormUrlEncodedContent(form));

    var jsonString = await response.Content.ReadAsStringAsync();
    var tree = JObject.Parse(jsonString);
    string token = tree["access_token"].Value<string>();

    return token;
}

在上面的代码中,await this.identityServerClient.PostAsync(uri, new FormUrlEncodedContent(form));返回Http错误代码400:第一次运行测试时(即,我在没有数据库的情况下运行)错误的请求。

在第一次运行期间,DbInitializer正确地创建了数据库,应用了迁移并植入了数据。然后,当测试客户端尝试获取令牌时,出现400错误。此后,在已经准备好数据库的情况下,当我再次运行集成测试时,它顺利通过了(我不会在随后的运行中更改对Identity Server的实际请求中的任何内容。)

编辑:

作为一种解决方法,我在Thread.Sleep(1000)之前添加了var response = await this.identityServerClient.PostAsync(uri, new FormUrlEncodedContent(form));,这似乎可以解决问题。但是,我真的很感谢有人可以向您说明这里发生的事情...

0 个答案:

没有答案