【发布时间】:2015-12-10 05:47:16
【问题描述】:
可能是愚蠢的问题,我第一次真正编写单元测试(我感到羞耻)。我正在使用 Xunit 和 AutoFixture。 所以,我有一些单元测试,我想用不同的输入数据组合来运行。
例如,假设我正在测试我的 DAL,并希望使用不同类型的存储库(例如内存和 SQL)测试相同的单元测试。我还需要创建一些其他数据,单元测试和存储库都将使用这些数据。 我的一些类需要通过工厂方法创建,因为它们没有任何公共构造函数。
我的理想是做类似的事情
[Theory, InMemoryRepository, SomeOtherData]
[Theory, SqlRepository, SomeOtherData]
// ... some other data combinations ...
public void SomeTest(IRepository repository, ISomeOtherData someOtherData)
{
// do some tests here
}
public class InMemoryRepositoryAttribute : AutoDataAttribute
{
public InMemoryRepositoryAttribute()
{
Fixture.Register<IRepository>(CreateRepository);
}
protected IRepository CreateRepository()
{
var data = Fixture.CreateMany<ISomeOtherData>().ToList(); // this will throw an exception "AutoFixture was unable to create an instance (...)" as my binding doesn't seem be available in the Fixture
var repository = new InMemoryDAL.Repository();
repository.Insert(data);
return repository;
}
}
public class SomeOtherDataAttribute : AutoDataAttribute
{
public SomeOtherDataAttribut()
{
Fixture.Register<ISomeOtherData>(CreateData);
}
protected ISomeOtherData CreateData()
{
string test = Fixture.Create<string>();
var data = (new SomeOtherDataFactory()).Create(test);
return data;
}
}
但这不起作用,因为我的两个 AutoDataAttribute 类似乎都基于单独的装置。 IE。我在 SomeOtherDataAttribute 中注册的任何内容似乎在我的 InMemoryRepositoryAttribute 实例中都不可用。
有没有办法解决这个问题并使用属性将不同的数据集组合到一个 Fixture 中?
或者您会建议什么替代方案 - 最好为每个数据组合创建单独的测试函数,并从那里显式调用 SomeTest()?
谢谢!
【问题讨论】:
标签: c# unit-testing xunit autofixture