如果断言失败,你如何执行拆解?

时间:2014-03-11 14:59:22

标签: unit-testing xunit.net autofixture

我正在构建一些集成测试,其中一个正在测试事务。我故意添加了一个提交来强制断言失败。但是,当发生这种情况时,执行将停止,我的拆卸将永远不会执行(应该删除添加的记录)。

如何设置此测试以便始终删除添加的记录,即使断言失败?

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)
    {
    }
}

1 个答案:

答案 0 :(得分:2)

这个怎么样?

//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());
}