本文介绍了使用异步方法在Teamcity上运行xUnit测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我进行了以下xUnit测试,该测试使用HttpClient调用Web服务器上的状态api方法.

I made the following xUnit test which is using a HttpClient to call a status api method on a webserver.

[Fact]
public void AmIAliveTest()
{
    var server = TestServer.Create<Startup>();

    var httpClient = server.HttpClient;
    var response = httpClient.GetAsync("/api/status").Result;

    response.StatusCode.Should().Be(HttpStatusCode.OK);
    var resultString = response.Content.ReadAsAsync<string>().Result;

    resultString.Should().Be("I am alive!");
}

该测试在本地运行良好.但是,当我提交代码并尝试在TeamCity构建服务器上运行相同的测试时,它将永远运行.我什至必须终止xunitRunner过程,因为停止构建不会停止该过程.

This test is running fine locally. But when I commit the code and try to run the same test on the TeamCity build server, it runs forever. I even have to kill the xunit runner process because stopping the build will not stop this process.

但是当我这样编写测试

[Fact]
public async void AmIAliveTest()
{
   var server = TestServer.Create<Startup>();

   var httpClient = server.HttpClient;
   var response = await httpClient.GetAsync("/api/status");

   response.StatusCode.Should().Be(HttpStatusCode.OK);
   var resultString = await response.Content.ReadAsAsync<string>();

   resultString.Should().Be("I am alive!");
}

它可以在本地以及在TeamCity上正常运行.

It runs fine locally and also on TeamCity.

我现在担心的是,我忘了像第二个变体一样编写测试,并且有时不定期地进行团队建设.

My concern is now that I forget to write the test like the second variant and that once in a while the teamcity build is hanging.

有人可以向我解释为什么在teamcity buildserver上运行的xUnit首先没有正确运行测试吗?对此有解决方案吗?

Can anybody explain to me why xUnit running on the teamcity buildserver is not running the test correctly in the first place? And is there a solution for this to solve this?

推荐答案

首先,我要检查您的xUnit版本-您应该运行最新发布的2.0.我怀疑您的本地版本可能已过时.

First, I'd check your xUnit versions - you should be running the recently-released 2.0. I suspect your local version may be out of date.

核心问题在这一行:

var resultString = response.Content.ReadAsAsync<string>().Result;

我怀疑您遇到了僵局的情况在我的博客上描述的. HttpClient在某些平台上具有某些无法正确使用ConfigureAwait(false)的方法,因此会遇到此死锁. xUnit 2.0将单线程SynchronizationContext安装到其所有单元测试中,这提供了另一半的死锁情况.

I suspect you're running into a deadlock situation that I describe on my blog. HttpClient has some methods on some platforms that do not properly use ConfigureAwait(false), and is thus subject to this deadlock. xUnit 2.0 installs a single-threaded SynchronizationContext into all its unit tests, which provides the other half of the deadlock scenario.

正确的解决方案是将Result替换为await,并将单元测试方法的返回类型从void更改为Task.

The proper solution is to replace Result with await, and to change the return type of your unit test method from void to Task.

这篇关于使用异步方法在Teamcity上运行xUnit测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 02:14