Che*_*tan 24 tdd unit-testing interface
例如,有一个接口IMyInterface
,有三个类支持这个接口:
class A : IMyInterface
{
}
class B : IMyInterface
{
}
class C : IMyInterface
{
}
Run Code Online (Sandbox Code Playgroud)
用最简单的方法,我可以编写三个测试类:ATest,BTest,CTest并分别测试它们.但是,由于它们支持相同的接口,因此大多数测试代码都是相同的,很难维护.如何使用简单易用的方法测试不同类支持的接口?
Tim*_*oyd 41
如果要使用NUnit作为示例对接口的不同实现者运行相同的测试:
public interface IMyInterface {}
class A : IMyInterface { }
class B : IMyInterface { }
class C : IMyInterface { }
public abstract class BaseTest
{
protected abstract IMyInterface CreateInstance();
[Test]
public void Test1()
{
IMyInterface instance = CreateInstance();
//Do some testing on the instance...
}
//And some more tests.
}
[TestFixture]
public class ClassATests : BaseTest
{
protected override IMyInterface CreateInstance()
{
return new A();
}
[Test]
public void TestCaseJustForA()
{
IMyInterface instance = CreateInstance();
//Do some testing on the instance...
}
}
[TestFixture]
public class ClassBTests : BaseTest
{
protected override IMyInterface CreateInstance()
{
return new B();
}
}
[TestFixture]
public class ClassCTests : BaseTest
{
protected override IMyInterface CreateInstance()
{
return new C();
}
}
Run Code Online (Sandbox Code Playgroud)
mdm*_*dma 20
要测试具有常见测试的接口而不管实现如何,您可以使用抽象测试用例,然后为接口的每个实现创建测试用例的具体实例.
抽象(基础)测试用例执行实现中立测试(即验证接口契约),而具体测试负责实例化要测试的对象,并执行任何特定于实现的测试.
归档时间: |
|
查看次数: |
21116 次 |
最近记录: |