所以我有一个使用 MSTest 的 Testclass,如果我一个一个地运行它们,每个测试都很好,但是如果我选择 2 个测试,即 can_register 和 can_register_existing_username,那么第二个测试失败(cannot_register_existing_username)。
我让我的 testclass 从一个看起来像这样的抽象类继承:
public abstract class RollbackCapabilities
{
private TransactionScope _transactionScope;
[TestInitialize]
public virtual void TestInitialize()
{
_transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions { Timeout = new TimeSpan(0, 10, 0) });
}
[TestCleanup]
public virtual void TestCleanup()
{
Transaction.Current.Rollback();
_transactionScope.Dispose();
}
}
如果我将此文件注释掉,那么它可以工作(但现在数据保留在我不想要的 test-db 中)。
使用上面的这个文件,第二个测试失败,测试看起来像这样
[TestMethod]
public void Can_Register()
{
//Arrange
AccountController ac = ControllerFactory.CreateAccountController();
RegisterModel model = new RegisterModel();
model.UserName = "TestUser";
model.Password= "TestPassword";
model.ConfirmPassword = "TestPassword";
//Act
ActionResult result = ac.Register(model);
//Assert
Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
Assert.AreEqual("Home", ((RedirectToRouteResult)result).RouteValues["controller"]);
Assert.AreEqual("Index", ((RedirectToRouteResult)result).RouteValues["action"]);
}
[TestMethod]
public void Cannot_Register_Existing_Username()
{
//Arrange
AccountController ac = ControllerFactory.CreateAccountController();
RegisterModel model = new RegisterModel();
model.UserName = "TestUser";
model.Password = "TestPassword";
model.ConfirmPassword = "TestPassword";
ac.Register(model);
RegisterModel model2 = new RegisterModel();
model2.UserName = "TestUser";
model2.Password = "OtherTestPassword";
model2.ConfirmPassword = "OtherTestPassword";
//Act
ActionResult result = ac.Register(model2);
//Assert
Assert.IsInstanceOfType(result, typeof(ViewResult));
Assert.AreEqual("", ((ViewResult)result).ViewName);
Assert.AreEqual(model2, ((ViewResult)result).ViewData.Model);
}
最后我得到的错误如下:
测试方法 Viducate.UnitTests.UserHandling.RegisterTests.Cannot_Register_Existing_Username 抛出异常:System.Data.EntityCommandExecutionException:执行命令定义时出错。有关详细信息,请参阅内部异常。---> System.Data.SqlClient.SqlException:对象名称“dbo.Users”无效。
那是我的问题,不是很大但很烦人,正如我提到的,如果我一次又一次地运行测试它可以工作,它也可以工作,但如果我注释掉我的 RollbackCapabilities 类,它会在数据库中留下数据