Xunit multiple IClassFixtures

白昼怎懂夜的黑 提交于 2019-12-05 08:53:21

First of all, let's recall when we want to use Class Fixtures in xUnit:

When to use: when you want to create a single test context and share it among all the tests in the class, and have it cleaned up after all the tests in the class have finished.

As you've said, you'd like to reuse methods from Zoo test class to implementation tests. Since implementations use inheritance, why not use inheritance for test classes too?

public abstract class Zoo
{
    protected IFixture Fixture;

    [Fact]
    public void TestAnimal()
    {
        //Arrange 
        int actualBonesCount = Fixture.BonesCount;
        int expectedBonesCount = 2;

        //Act & Assert
        Assert.Equal(expectedBonesCount, actualBonesCount);
    }
}

public class BirdTests : Zoo, IClassFixture<Bird>
{
    public BirdTests(Bird fixture)
    {
        Fixture = fixture;
    }
}

public class TigerTests : Zoo, IClassFixture<Tiger>
{
    public BirdTests(Tiger fixture)
    {
        Fixture = fixture;
    }
}

Still, I don't really get how would you like for each test to pass as you've hardcoded BonesCount to 2 in a generic test.

This is solution i came to after your comment. Thank you very much!

public static IEnumerable<object[]> TestCases = 
new TheoryData<Animal>{ new Bird { Eyes = 2 } };

[Theory]
[MemberData(nameof(TestCases))]
public void TestEyes(Animal email)
{
//Arrange & Act & Assert
}

;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!