运行 个具有共同连接对象和不同连接状态的单元测试用例

Running unit test cases with common connection object and different connection states

我正在使用 xUnit 1.9 运行 一堆测试用例,它们都共享同一个资源连接,但它们分为三个不同的类别,需要连接处于三个不同的状态。

我创建了一个处理连接的夹具 class 和三个不同的 classes 来保存需要三种不同连接状态的三类测试用例。

现在我相信 fixture 对象只创建一次,通过构造函数只连接一次,最后通过 Dispose 方法只断开连接一次。我没听错吗?

我如何才能为每个 class(方法组)设置一次连接状态而不是每次都为每个方法设置状态(通过将代码添加到每个 class 构造函数)?

虚拟代码:

public class Fixture : IDispose
{
    public Fixture() { connect(); }
    public void Dispose() { disconnect(); }
    public void SetState1();
    public void SetState2();
    public void SetState3();
}

public class TestCasesForState1 : IUseFixture<Fixture>
{
    public void SetFixture(fix) { fix.SetState1() } // will be called for every test case. I'd rather have it being called once for each group

    [Fact]
    public void TestCase1();

    ...
}

public class TestCasesForState2 : IUseFixture<Fixture>
{
    public void SetFixture(fix) { fix.SetState2() } // will be called for every test case. I'd rather have it being called once for each group

    [Fact]
    public void TestCase1();

    ...
}

public class TestCasesForState3 : IUseFixture<Fixture>
{
    public void SetFixture(fix) { fix.SetState3() } // will be called for every test case. I'd rather have it being called once for each group

    [Fact]
    public void TestCase1();

    ...
}
public class Fixture : IDispose {

    public Fixture() { connect(); }

    public void Dispose() { disconnect(); }

    static bool state1Set;
    public void SetState1() {
        if(!state1Set) {
            state1Set = true;
            //...other code
            changeState(1);
        }
    }

    static bool state2Set;
    public void SetState2() {
        if(!state2Set) {
            state2Set = true;
            //...other code
            changeState(2);
        }
    }

    static bool state3Set;
    public void SetState3() {
        if(!state3Set) {
            state3Set = true;
            //...other code
            changeState(3);
        }
    }
}