I try integration testing with rollback. I use SQL server. My setup, which I took from this topic, looks like this:
private TransactionScope scope;
[TestInitialize]
public void Initialize()
{
this.scope = new TransactionScope();
}
[TestCleanup]
public void TestCleanup()
{
this.scope.Dispose();
}
Testing method:
var newUser = new UserDetailModel();
newUser.Id = 1;
newUser.Email = "[email protected]";
newUser.FirstName = "Test";
newUser.LastName = "User";
newUser.UserName = "test.user";
await userManager.AddAsync(newUser);
There shouldn't be a new user in db after the test is completed, but I have new user in db even test is finished. I even tried the same method with Database.BeginTransaction():
using (var transaction = unitOfWork.GetDbContext().Database.BeginTransaction())
{
var newUser = new UserDetailModel();
newUser.Id = 1;
newUser.Email = "[email protected]";
newUser.FirstName = "Test";
newUser.LastName = "User";
newUser.UserName = "test.user";
await userManager.AddAsync(newUser);
transaction.Rollback();
}
Rollback doesn't work either.
To make TransactionScope and async work properly use .NET 4.5.1. or later and You have to explicitly opt-in the transaction flow across thread continuations by specifying TransactionScopeAsyncFlowOption.Enabled like this:
new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)
Read more on the topic: https://particular.net/blog/transactionscope-and-async-await-be-one-with-the-flow
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With