我可以创建用于测试的环境事务吗?

Can I create an ambient transaction for testing?

我当前的系统有一个相当激进的数据层,它通过调用静态方法为我创建一个 SqlDatabase 实例。我传入一个存储过程名称(字符串),奇迹就发生了。

我想尝试对这个疯狂的系统进行一些测试,因此想控制数据库中的内容。

意识到这个结构

[Test]
public void Should_do_some_thing()
{   
  using (var scope = new TransactionScope())
            {
                CleanUpDatabase();
                SetupDatabaseData();

                //Run Test

                Assert.That(someResult,Is.EqualTo("ExpectedValue");

                scope.Dispose();
            }
}

做我想做的事(没有数据库更改在测试之外持续存在)如果我可以在 [SetUp] 方法中设置事务并在 [TearDown] 部分中删除而不提交,那显然会更好.

这可能吗?

请注意,我不能在 command 对象或其他对象上调用任何方法...

您可以使用 TestInitializeTestCleanup 来设置 up/clean up:

private TransactionScope scope;

[TestInitialize]
public void TestInitialize()
{
    scope = new TransactionScope();
    CleanUpDatabase();
    SetupDatabaseData();
}

[Test]
public void Should_do_some_thing()
{   
    //Run Test

    Assert.That(someResult,Is.EqualTo("ExpectedValue");
}

[TestCleanup]
public void CleanUp()
{
    scope.Dispose();
}

您可能需要添加错误处理等,但这是它的基础:

TestInitialize:

Identifies the method to run before the test to allocate and configure resources needed by all tests in the test class. This class cannot be inherited.

TestCleanUp:

Identifies a method that contains code that must be used after the test has run and to free resources obtained by all the tests in the test class. This class cannot be inherited.

如果您使用的是 NUNIT,那么您可以分别使用 [SetUp][TearDown] 而不是 [TestInitialize][TestCleanUp]