简体   繁体   中英

What is the best way to test multiple derived types using Xunit?

I have an interface IFoo

public interface IFoo
{
    void DoSomeStuff();
}

And I have two derived types FooImpl1 and FooImpl2 :

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

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

I have a test class which tests IFoo contract of FooImpl1 :

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

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

        //Assertions.
    }

How can I reuse this test class to test both FooImpl1 and FooImpl2 ?

How about having base class for IFoo tests with abstract method returning appropriate implementation?

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

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

Now, all derived types have to do is simply provide that one instance:

public class FooImpl1Tests : FooTestsBase
{
    protected override IFoo GetTestedInstance()
    {
        return new FooImpl1();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM