I'm looking for a project/tool that will insert data into a database before a test and roll it back after a test has run.
I know that ruby on rails has yaml fixtures, so I was hoping there is a project out there for .net projects.
I'm looking for a project/tool that will insert data into a database before a test and roll it back after a test has run.
I know that ruby on rails has yaml fixtures, so I was hoping there is a project out there for .net projects.
有几种很好的方法可以为 .NET 中的测试提供数据。一种是使用 NUnit 内置的功能,例如参数化测试和理论。
TestCaseAttribute允许您轻松地将硬编码数据提供给测试,如下面的 nunit.org 示例所示:
[TestCase(12,3, Result=4)]
[TestCase(12,2, Result=6)]
[TestCase(12,4, Result=3)]
public int DivideTest(int n, int d)
{
return( n / d );
}
TestCaseDataAttribute让您在提供数据(例如从数据库中返回数据)方面更加花哨。
另一个经常使用的技巧是依赖交易。基本上,在测试之前启动一个事务,然后回滚。这甚至可以使用基类自动化,因此您的测试根本不处理事务本身。例如,您可能有一个用于测试夹具的基类,如下所示:
public class TestBase
{
private TransactionScope _transacation;
[SetUp]
public virtual void InitializeTest()
{
//NOTE: Base class TestInitialize methods are called before test Initialize methods in derived class.
// Setup a DB transcation to roll everything back after the tests.
if (_transacation != null)
throw new Exception("old transacation still exists");
// Give a long timeout on this transacation for debugging...
_transacation = new TransactionScope(TransactionScopeOption.RequiresNew, TimeSpan.FromSeconds(60));
}
[TearDown]
public virtual void CleanupTest()
{
// Roll all the changes made during the test back.
_transacation.Dispose();
_transacation = null;
}
}
由于基类上的 TestInitialize修饰方法在派生类中的 TestInitialize 方法之前被调用,因此您甚至可以在父类的 TestInitialize 方法中将一些数据添加到数据库中。
父类可能如下所示:
[TestFixture]
public class MyClassTests : TestBase
{
[TestFixtureSetUp]
public void InitializeUnit()
{
//Setup mocks...
}
[SetUp]
public override void InitializeTest()
{
base.InitializeTest();
// Add test data to database
}
[Test]
public void RealTest()
{
...
}
}
我使用 Sql Server Compact Edition 并每次都重新生成一个新的数据库副本(只需复制一个初始数据库就可以了),如果在只读模式下使用,多个测试可以共享同一个数据库文件。
有一些陷阱,不支持可编程性,但它适用于我需要它的基础知识。它的速度也出奇的快。