Per*_*eck 12 c# inheritance nunit
所以基本上我有一个域对象和一个可以用该对象进行CRUD操作的通用存储库.
public interface IBaseRepository<T> where T : BaseEntity
{
void Add(T entity);
void Remove(T entity);
T ById(int id);
IEnumerable<T> All();
}
Run Code Online (Sandbox Code Playgroud)
所以我有几个这个接口的实现,每个域对象一个.
我想写一些集成测试(使用nunit),为此我想我会做一个BaseRepositoryTest - 像这样:
public abstract class BaseRepositoryTests<T> where T : BaseEntity
{
public abstract IBaseRepository<T> GetRepository();
public abstract T GetTestEntity();
[Test]
public void AddWhenCallingAddsObjectToDatabase()
{
IBaseRepository<T> repository = GetRepository();
T entity = GetTestEntity();
repository.Add(entity);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,对于每个域对象,我将不得不实现如何初始化存储库以及如何创建测试实体,这似乎是公平的,因为它们会有所不同......
我现在要做的就是编写实际的测试夹具吗?像这样:
[TestFixture]
public class FooRepositoryTests: BaseRepositoryTests<Foo>
{
public override IBaseRepository<Foo> GetRepository()
{
throw new NotImplementedException();
}
public override Foo GetTestEntity()
{
throw new NotImplementedException();
}
}
Run Code Online (Sandbox Code Playgroud)
这应该让我开始并给我一个失败的测试,因为throw将打破它(我也尝试实际实现方法没有运气).但是测试人员(尝试了nunits GUI和resharpers测试跑步者)只是忽略了我的基础测试!它显示了所有 - 但报告为已忽略.
所以我做了一点挖掘... NUnit在TextFixtureAttribute上有这个属性,让你指定你正在测试的是什么类型,所以我试着把属性
[TestFixture(typeof(Foo))]
Run Code Online (Sandbox Code Playgroud)
首先是Base,还有Foo版本.当放在Foo版本时,它仍然只是忽略了从基础的测试,当我把它放在基础上...好吧它变成红色因为方法抛出异常,这将是好的,除非即使我做实际的实现在FooTests中,它们仍然无法工作(显然,基于TestFixture属性的Base测试永远不会知道哪些类继承它,所以如何知道找到实现).
那么我该坚持做什么?我可以在基础测试类虚拟中进行测试,然后在FooBaseRepositoryTests中覆盖它,只是从base调用实现,这是一个蹩脚的解决方案,我认为......
还需要做什么?我错过了什么吗?请帮忙,有人...... :)
当您[TestFixture(typeof(Foo))]在夹具类上使用该属性以便将其用于不同类型时;它不应该是抽象的。
如果在 Foo 固定装置上使用,该类应该是通用的,而不是为 Foo 键入的。
来自文档:
[TestFixture]
public class AbstractFixtureBase
{
...
}
[TestFixture(typeof(string))]
public class DerivedFixture<T> : AbstractFixtureBase
{
...
}
Run Code Online (Sandbox Code Playgroud)
http://www.nunit.org/index.php?p=testFixture&r=2.5.5