在回答另一个SO问题时,我在使用Xunit和Visual Studio 2015 ctp6运行异步任务时遇到了一个问题。
这是代码:
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.TestHost;
using Microsoft.Framework.DependencyInjection;
using Xunit;
using Microsoft.AspNet.Builder;
using System.Net.Http;
namespace Multi.Web.Api
{
public class TestServerHelper : IDisposable
{
public TestServerHelper()
{
ClientProvider = new TestClientProvider();
ApiServer = TestServer.Create((app) =>
{
app.UseServices(services =>
{
services.AddTransient<IClientProvider>(s => ClientProvider);
});
app.UseMulti();
});
}
public TestClientProvider ClientProvider { get; private set; }
public TestServer ApiServer { get; private set; }
public void Dispose()
{
ApiServer.Dispose();
ClientProvider.Dispose();
}
}
public class MultiMiddlewareTest : IClassFixture<TestServerHelper>
{
TestServerHelper _testServerHelper;
public MultiMiddlewareTest(TestServerHelper testServerHelper)
{
_testServerHelper = testServerHelper;
}
[Fact]
public async Task ShouldReturnToday()
{
using (HttpClient client = _testServerHelper.ApiServer.CreateClient())
{
var response = await client.GetAsync("http://localhost/today");
String content = await response.Content.ReadAsStringAsync();
Assert.Equal(content, "2015-04-15 count is 1");
}
}
[Fact]
public async Task ShouldReturnYesterday()
{
using (HttpClient client = _testServerHelper.ApiServer.CreateClient())
{
var response = await client.GetAsync("http://localhost/yesterday");
String content = await response.Content.ReadAsStringAsync();
Assert.Equal(content, "2015-04-14 count is 1");
}
}
}
}
在Visual Studio TestExplorer中,当一个接一个地运行测试(右键单击并选择调试选定的测试)时没关系,但是当全部运行时,没有一个通过,我有以下错误
Message : Response status code does not indicate success : 404 (Not Fount)
所有代码都可以在另一个 so 问题上找到,在这个问题中,我回答了如何使用 TestServer 的多个实例来模拟外部 API。我认为这与一些同步上下文有关。
我想我写我的助手的方式不好,因为我看到它在调用实际完成之前会处理对象(有时不是...... 有人有同样的问题并对此有解决方案吗?
更新:链接到github上的完整代码
默认情况下,当您运行所有测试时,Xunit 会并行运行您的测试;我猜这可能会导致您的测试服务器发生冲突并产生副作用。(我不确定你在project.json中使用了什么包,所以我可能弄错了。 查看 Xunit 文档中的并行运行测试,找到适合您的解决方案。
选项:
- 使用
CollectionAttribute
,例如[Collection("Localhost http server")]
。 - 在命令行上指定
-parallel none
作为选项。 - 使用程序集属性更改默认行为,例如
[assembly: CollectionBehavior(DisableTestParallelization = true)]
更新 2:
更新 1 是一个红鲱鱼,所以我完全删除了它。从FakeExternalApi
中间件中删除await next(context);
似乎已经消除了间歇性问题。@Tratcher的评论表明"呼叫下一步...不鼓励",但我不确定这是否与 OwinMiddleware 特别相关,或者它是否是很好的一般建议,但它似乎适用于这里。