2

我有一个界面IFoo

public interface IFoo
{
    void DoSomeStuff();
}

我有两种派生类型FooImpl1FooImpl2

public class FooImpl1 : IFoo
{
    public void DoSomeStuff()
    {
        //...
    }
}

public class FooImpl2 : IFoo
{
    public void DoSomeStuff()
    {
        //Should do EXACTLY the same job as FooImpl1.DoSomeStuff()
    }
}

我有一个测试类测试IFoo合同FooImpl1

    private static IFoo FooFactory()
    {
        return new FooImpl1();
    }

    [Fact]
    public void TestDoSomeStuff()
    {
        IFoo foo = FooFactory();

        //Assertions.
    }

我怎样才能重用这个测试类来测试FooImpl1FooImpl2

4

1 回答 1

3

IFoo使用抽象方法返回适当实现的测试基类怎么样?

public abstract class FooTestsBase
{
    protected abstract IFoo GetTestedInstance();

    [Fact]
    public void TestDoSomeStuff()
    {
        var testedInstance = GetTestedInstance();
        // ...
    }
}

现在,所有派生类型只需提供一个实例:

public class FooImpl1Tests : FooTestsBase
{
    protected override IFoo GetTestedInstance()
    {
        return new FooImpl1();
    }
}
于 2012-09-09T12:26:03.800 回答