这安全吗? - NUnit 基类打开并回滚 TransactionScope
我认为为 NUnit 测试装置创建一个基类会很好,该基类在设置阶段打开 TransactionScope,然后在拆卸过程中回滚事务。 像这样的事情:
public abstract class TestFixtureBase
{
private TransactionScope _transaction;
[TestFixtureSetUp]
public void TestFixtureSetup()
{
_transaction = new TransactionScope();
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
if (_transaction != null)
{
_transaction.Dispose();
}
}
}
你认为这是个好主意吗?
显然,该数据库只是一个测试数据库,而不是一个实时数据库,但如果它充满了单元测试中的垃圾数据,它仍然会很烦人。
当运行涉及大量数据访问的单元测试时,其他人会做什么?
I was thinking it would be nice to create a base class for NUnit test fixtures that opens a TransactionScope during the SetUp phase, then rolls back the transaction during tear down.
Something like this:
public abstract class TestFixtureBase
{
private TransactionScope _transaction;
[TestFixtureSetUp]
public void TestFixtureSetup()
{
_transaction = new TransactionScope();
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
if (_transaction != null)
{
_transaction.Dispose();
}
}
}
Do you think this is a good idea?
Obviously the database is just a test database, not a live database, but it would still be annoying if it filled up with junk data from the unit tests.
What do other people do when running unit tests that involve a lot of data access?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你在这里要小心。 如果您打开多个数据库连接,TransactionScope 会将事务提升为分布式事务。 我发现在开始运行测试之前编写一些简单的 SQL 来清除测试类感兴趣的表会更容易。
编辑:通常我会将任何涉及数据库的测试称为集成测试,因为它涉及另一个系统。 通常,我会在对代码进行单元测试时模拟数据库。
You want to be careful here. TransactionScope is going to promote the transaction to a distributed transaction if you open up more than one connection to the database. I find that it is easier just to write some simple SQL that clears out the tables of interest to my test class before I start running the test.
EDIT: Normally I would call any test that touches the database an integration test since it involves another system. Typically, I will mock out the database when unit testing my code.
我使用过 XtUnit
它在单元测试结束时自动回滚。 您只需向测试添加 [Rollback] 属性即可。 它是 NUnit 或 MbUnit 的扩展
I've used XtUnit
It automatically rolls back at the end of a unit test. You can simply add a [Rollback] attribute to the test. It's an extension to NUnit or MbUnit