我有一组基本测试,用于测试一个接口的多个实现。我对此建模的方式是创建一个带有忽略属性的基本文本夹具。
[TestFixture]
[Ignore]
public class BaseTests
{
// Use your imagination for the actual name
public virtual ITestableThing GetConcrete()
{
return null;
}
// All of my unit tests here
}然后为每个接口实现编写一个子类:
public class ConcreteThingTests : BaseTests
{
public override ITestableThing GetConcrete()
{
return new ConcreteThing();
}
}这很好,因为我在一个地方拥有所有实现的所有测试,而子类只是指定实现。
问题是,我必须将忽略属性放在基类上,否则NUnit将尝试运行测试(并失败)。
正因为如此,我的测试结果总是被一组被忽略的测试弄得乱七八糟,虽然这不是什么大事,但我认为可能会有一个更好的模式来避免忽略测试。
那么,我是否实现了测试夹具继承错误?
发布于 2013-08-03 16:10:13
您通常会在具体的测试类上设置测试属性,而不是基类。
由于您似乎对多个类测试相同的功能,所以可以跳过整个测试层次结构,并将要测试的具体类注入到测试基类中。
要使用NUnit实现这一点,您可以使用带有类工厂方法的TestCaseSource属性作为参数。在这里可以找到一个例子:How to pass dynamic objects into an NUnit TestCase function?
为您的特定情况编写一些代码,如下所示:
/// <summary>
/// Earlier known as your BaseTests class
/// </summary>
[TestFixture]
public class TestOfConcreteImplementationsOfInterface
{
[TestCaseSource("CreateConcretes")]
[Test]
public void VerifyImplementations(IWhatever thing)
{
int input = 42;
int result = thing.DoSomething(input);
Assert.That(result, Is.EqualTo(input));
}
/// <summary>
/// Factory method for the concrete classes. If you want this in a seperate class, you can do that too using the
/// ctor public TestCaseSourceAttribute(Type sourceType, string sourceName);
/// </summary>
public IEnumerable<IWhatever> CreateConcretes
{
get
{
yield return new A();
yield return new B();
}
}
}
public interface IWhatever
{
int DoSomething(int x);
}
public class A : IWhatever
{
public int DoSomething(int x)
{
return x;
}
}
public class B : IWhatever
{
public int DoSomething(int x)
{
return x;
}
}发布于 2014-03-25 14:45:03
如果将基类标记为抽象,则NUnit测试运行程序将忽略它:
public abstract class BaseTests
{
}https://stackoverflow.com/questions/18033985
复制相似问题