我有一些旧的 MbUnit 代码,如下所示:
public class MyFixture {
[SetUp]
public void SetUp() {
// Add data to database
}
[Test, Rollback]
public void DoTest() {
// Tests with the data
}
}
我的新 NUnit Rollback 属性看起来有点像这样:
public class RollbackAttribute : TestActionAttribute
{
public override void BeforeTest(TestDetails testDetails)
{
// Begin transaction
}
public override void AfterTest(TestDetails testDetails)
{
// Abort transaction
}
}
回滚应该回滚在 SetUp 方法中添加的新数据以及测试本身期间的任何修改。不幸的是,NUnit 的 BeforeTest 似乎在夹具的 SetUp 方法之后运行,因此在 SetUp 期间添加的数据不会回滚。
有没有办法在SetUp之前运行BeforeTest?
一个选项是基类,并用 SetUp 和 TearDown 中的附加代码替换现有的 Rollback 属性,但是我的一些测试需要在事务之外运行(它们在测试运行期间自己创建多个事务),因此添加事务所有测试用例都需要小心。我宁愿找到一个可以重用现有回滚属性的解决方案。
最佳答案
Is there a way to run BeforeTest before SetUp?
我不这么认为,请参阅例如this related discussion on google groups 。正在讨论的问题非常相似,正如您所看到的,SetUp
方法中的代码甚至会在测试夹具级别使用的 BeforeTest
方法之前运行(您将其置于测试级别) )。
从我的角度来看,解决方法是从 SetUp
方法中删除 SetUpAttribute
并在开头显式调用 SetUp
方法每个测试,即:
public class MyFixture
{
public void SetUp()
{
// Add data to database
}
[Test, Rollback]
public void DoTest()
{
SetUp();
// Tests with the data
}
}
你的问题也让我想起了marc_s在this SO thread中提出的问题。问题与您的问题无关,但他使用了与我上面提出的相同的构造,因此这也许不是一个坏主意。
编辑:
Here是 NUnit 的 github 上的一个开放问题。但仍然要求订单:
BeforeTest (BaseFixture)
BaseSetUp BeforeTest (Fixture)
SetUp
BeforeTest (Test)
Test AfterTest (Test)
TearDown AfterTest (Fixture)
BaseTearDown AfterTest (BaseFixture)
所以不完全是你想要的,“BeforeTest(测试)”将在SetUp之后执行。
关于nunit - NUnit 中的 TestActionAttribute 可以在设备自己的 SetUp 方法之前运行 BeforeTest 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31342538/