我使用xUnit 1.9运行一堆测试用例,所有测试用例都与资源共享相同的连接,但它们分为三个不同的类别,要求连接处于三种不同的状态。
我创建了一个处理连接的fixture类和三个不同的类来保存需要三种不同连接状态的三类测试用例。
现在我相信夹具对象只能创建一次,只能通过构造函数连接一次,最后只通过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();
...
}
答案 0 :(得分: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);
}
}
}