我正在构建一些集成测试,其中之一是测试事务。 我故意添加了一个Commit来强制断言失败。 但是,当发生这种情况时,执行将停止,并且我的拆卸永远不会执行(这应该删除添加的记录)。
如何设置此测试,以便即使断言失败,添加的记录也始终被删除?
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)
{
}
}
这个怎么样?
//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());
}
阅读你的问题,我发现你没有将其他对存储库的请求包装在 try 块中,所以我假设这不是你需要检查的。
这是我的评论:
Assert.Null
运算符,您可以使用它来代替 Assert.True
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();
var user = uow.UserRepository.Get(x => x.Email == anonEmail).FirstOrDefault();
//Teardown
if (user != null)
{
uow.UserRepository.Delete(user);
}
//Assert
Assert.Null(user);