我认为您可以通过使用包含一些测试的抽象基类以及获取特定实现的抽象方法来解决此问题。
这仍然需要在每个具体的实现测试类中编写一些代码,但应该确保如果您从基类更改实现,您的构造函数仍然会被测试。
我刚刚做了一些类似的事情来测试一个方法,该方法对于许多实现来说是无操作的(它只返回给定的内容),但对于某些实现它会做一些事情,因此无操作代码测试在具有抽象方法的单个基类来获取要测试的对象(获取无操作方法所在的接口实例),以及应该只是无操作方法的具体实现扩展该类并覆盖抽象方法以返回我们要测试方法的类的实例。
这帮助我解决了我的问题,希望它也能帮助你。
public abstract class BaseClass
{
public abstract void CallConstructor(SomeType arg1, SomeType2 arg2);
[Test]
public void Constructor_WhenArg1IsNull_ArgumentNullExceptionIsThrown()
{
Assert.Throws<ArgumentNullException>(()=>CallConstructor(null, new SomeType2()));
}
[Test]
public void Constructor_WhenArg2IsNull_ArgumentNullExceptionIsThrown()
{
Assert.Throws<ArgumentNullException>(()=>CallConstructor(new SomeType(), null));
}
}
[TestFixture]
public class ConcreteImplementation1Tests : BaseClass
{
public override void CallConstructor(SomeType arg1, SomeType2 arg2)
{
new ConcreteImplementation1(arg1,arg2);
}
}
[TestFixture]
public class ConcreteImplementation2Tests : BaseClass
{
public override void CallConstructor(SomeType arg1, SomeType2 arg2)
{
new ConcreteImplementation2(arg1,arg2);
}
}
除此之外,同样的技术可用于测试常见的
实现接口的所有类的功能。以 IList 为例:
public abstract class ListImplementationsCommonTests
{
public abstract IList GetListImplementation();
[Test]
public void Add_WhenValidItemIsAdded_ItCanBeFound()
{
IList list = GetListImplementation();
object item = new Object();
list.Add(item);
Assert.That(list.Contains(item));
}
[Test]
public void Add_WhenNullIsAdded_ArgumentNullExceptionIsThrown()
{
IList list = GetListImplementation();
Assert.Throws<ArgumentNullException>(()=>list.Add(null));
}
...
//more common tests
...
}
然后可以使用相同的代码测试 IList 的每个实现(如 ArrayList、LinkedList、DoubleLinkedList、SortedList 等),而无需一次又一次地重复相同的测试:
[TestFixture]
public class ArrayListTests: ListImplementationCommonTests
{
public override IList GetListImplementation()
{
return new ArrayList();
}
...
//Extra specific tests for the ArrayList
}
[TestFixture]
public class LinkedListTests: ListImplementationCommonTests
{
public override IList GetListImplementation()
{
return new LinkedList();
}
...
//Extra specific tests for the LinkedList
}
[TestFixture]
public class SortedListTests: ListImplementationCommonTests
{
public override IList GetListImplementation()
{
return new SortedList();
}
...
//Extra specific tests for the SortedList
}