我正在使用xUnit 2.0 collection fixtures在许多不同的测试类之间共享一个通用的数据库设置/拆卸。 fixture还提供了一些辅助属性,因此我将它注入每个测试类。
我在文档中重新创建了示例,但是当我运行测试时,它立即失败:
以下构造函数参数没有匹配的fixture数据:IntegrationTestFixture fixture
无论我是使用xUnit Facts还是使用Theories,或者我正在使用哪个测试运行器,这似乎都会发生。
夹具:
public class IntegrationTestFixture : IDisposable
{
public IntegrationTestFixture()
{
// (setup code)
this.GeneratedTestName = [randomly generated];
}
public void Dispose()
{
// (teardown code)
}
public string GeneratedTestName { get; private set; }
}
集合定义:
[CollectionDefinition("Live tests")]
public class IntegrationTestCollection : ICollectionFixture<IntegrationTestFixture>
{
// Intentionally left blank.
// This class only serves as an anchor for CollectionDefinition.
}
测试:
[CollectionDefinition("Live tests")]
public class SomeTests
{
private readonly IntegrationTestFixture fixture;
public SomeTests(IntegrationTestFixture fixture)
{
this.fixture = fixture;
}
[Fact]
public void MyTestMethod()
{
// ... test here
}
}
这是一个愚蠢的错误,我花了一点时间弄清楚它为什么不起作用:
[CollectionDefinition]
继续进行集合定义类,但[Collection]
继续进行测试类。我在自动驾驶仪上并没有注意到这一点。
如果你在不同的类上有多个同名的[CollectionDefinition]
属性,你也会得到这个。只需使用一个!
在我的例子中,夹具和集合在一个共享的测试组件中。我发现XUnit DI找不到它。所以,我必须定义一个夹具,它继承共享程序集中的那些类,以便在让它在我的测试类中注册时共享功能。
在我的情况下,我忘了继承IClassFixture
界面...
错误...
public class DatabaseIntegrationTests
{
正确...
public class DatabaseIntegrationTests : IClassFixture<DatabaseFixture>
{
我有同样的错误,但对我来说问题是我忘了制作CollectionDefinition
类public
,例如
错误
[CollectionDefinition("Live tests")]
class IntegrationTestCollection : ICollectionFixture<IntegrationTestFixture>
{
// Intentionally left blank.
// This class only serves as an anchor for CollectionDefinition.
}
正确
[CollectionDefinition("Live tests")]
public class IntegrationTestCollection : ICollectionFixture<IntegrationTestFixture>
{
// Intentionally left blank.
// This class only serves as an anchor for CollectionDefinition.
}
如果Collection的构造函数抛出错误,也会发生这种情况。您可能需要通过其他方法调试该代码,因为xUnit提供的错误消息在这种情况下没有帮助。
我们的许多TestFixture类都有相似的名称。因此,请确保定义上的测试夹具类型与传递到包含测试的类的构造函数的类型完全匹配。
我刚刚遇到这个问题,我不得不将集合定义放入与测试类相同的名称空间中。不只是相同的组件。