I'm building some integration tests, and one of them is testing transactions. I intentionally added a Commit to force the assert to fail. However when this occurs, execution stops and my teardown is never executed (which should remove the added record).
How can I setup this test so that the added record is always deleted, even if the assert fails?
using (var uow = new UnitOfWork(context))
{
//Arrange
var fixture = new Fixture();
var anonEmail = fixture.Create<string>("email");
//Act
uow.UserRepository.Insert(new DAL.Models.User()
{
Email = anonEmail,
FullName = fixture.Create<string>()
});
uow.Save();
uow.Commit(); //intentionally added to force Assert to fail!
uow.Rollback();
//Assert
var user =
uow.UserRepository.Get(x => x.Email == anonEmail).FirstOrDefault();
Assert.True(user == null);
//Teardown
try
{
uow.UserRepository.Delete(
uow.UserRepository.Get(x => x.Email == anonEmail).FirstOrDefault());
}
catch (Exception)
{
}
}
How about this?
//Arrange
var uow = new UnitOfWork(context);
var fixture = new Fixture();
var anonEmail = fixture.Create<string>("email");
try
{
//Act
uow.UserRepository.Insert(new DAL.Models.User()
{
Email = anonEmail,
FullName = fixture.Create<string>()
});
uow.Save();
uow.Commit(); //intentionally added to force Assert to fail!
uow.Rollback();
//Assert
var user =
uow.UserRepository.Get(x => x.Email == anonEmail).FirstOrDefault();
Assert.True(user == null);
}
//Teardown
finally
{
uow.UserRepository.Delete(
uow.UserRepository.Get(x => x.Email == anonEmail).FirstOrDefault());
}