C#使用回滚进行集成测试

时间:2017-08-15 14:05:24

标签: c# integration-testing

我尝试使用回滚进行集成测试。我用的是SQL服务器。我从这个topic中获取的设置如下所示:

private TransactionScope scope;

[TestInitialize]
public void Initialize()
{
    this.scope = new TransactionScope();
}

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

测试方法:

var newUser = new UserDetailModel();
newUser.Id = 1;
newUser.Email = "test@test.cz";
newUser.FirstName = "Test";
newUser.LastName = "User";
newUser.UserName = "test.user";
await userManager.AddAsync(newUser);

测试完成后,不应该在db中成为新用户,但我在db中有新用户,即使测试已完成。我甚至用 Database.BeginTransaction()

尝试了相同的方法
using (var transaction = unitOfWork.GetDbContext().Database.BeginTransaction())
{
    var newUser = new UserDetailModel();
    newUser.Id = 1;
    newUser.Email = "test@test.cz";
    newUser.FirstName = "Test";
    newUser.LastName = "User";
    newUser.UserName = "test.user";
    await userManager.AddAsync(newUser);

    transaction.Rollback();
}

回滚也不起作用。

1 个答案:

答案 0 :(得分:1)

要使TransactionScope和异步正常工作,请使用.NET 4.5.1。或者稍后,您必须通过指定TransactionScopeAsyncFlowOption.Enabled来明确地选择跨线程延续的事务流:

new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)

详细了解该主题:https://particular.net/blog/transactionscope-and-async-await-be-one-with-the-flow