所以我有一个使用MSTest的Testclass和每个测试伟大的工作,如果我运行他们一,然而,如果我选择2测试,即can_register和cannot_Register_existing_username那么第二次失败cannot_register_existing_username)。MSTest失败时,我运行全部,但工作,否则
我已经让我的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();
}
}
如果我评论这个文件出来,然后它工作(但现在的数据保留在其中我不测试-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类
您确定您的TestInitialize和TestCleanup方法是以这种方式执行的吗? – Schaliasos 2013-03-23 14:35:25
你确定'Transaction.Current.Rollback();'正在执行吗?尝试在该线上放置一个断点并调试测试,看看它是否是。 – rhughes 2013-03-23 14:45:43
事情正在被调用顺序首先intilialize,然后test1,然后清理,然后初始化,然后test2然后崩溃 – 2013-03-23 16:25:41