2

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

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

现在我相信夹具对象只被创建一次,并且只通过构造函数连接一次,最后只通过 Dispose 方法断开一次。我说对了吗?

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

虚拟代码:

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();

    ...
}
4

1 回答 1

1
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);
        }
    }
}
于 2016-04-18T21:51:00.200 回答