【问题标题】:Running unit test cases with common connection object and different connection states运行具有通用连接对象和不同连接状态的单元测试用例
【发布时间】:2016-04-19 05:51:00
【问题描述】:

我正在使用 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();

    ...
}

【问题讨论】:

    标签: c# xunit fixture


    【解决方案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-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-15
      • 1970-01-01
      • 2019-04-16
      • 2021-10-15
      • 1970-01-01
      相关资源
      最近更新 更多