我在测试我的 Nhibernate 存储库时遇到了一个奇怪的问题。
我有 10 个单元测试,如下所示。每次批量运行它们时,第一个失败,其余的成功。如果一个一个运行它们,它们都会失败。如果在我的测试运行之前重新启动 MSDTC,它有时会像以前一样运行,有时所有测试都会成功。我找不到它为什么会这样的模式。
我希望事务回滚,以便为每个测试从一个干净的数据库开始,从而处理事务。
由于此错误,测试/测试失败:
System.Data.SqlClient.SqlException: MSDTC on server 'MYCOMPUTERNAME\SQLEXPRESS' is unavailable.
我的测试是这样的:
[TestInitialize]
public void MyTestInitialize()
{
_transactionScope = new TransactionScope();
}
[TestCleanup]
public void MyTestCleanup()
{
if (_transactionScope != null)
{
_transactionScope.Dispose();
_transactionScope = null;
}
}
[TestMethod]
[TestCategory("RepositoryTests")]
public void RepositoryCanSaveAProduct()
{
var platform = ProductObjectMother.CreatePlatform("100010", "Supplier 10");
var mainsegment = ProductObjectMother.CreateMainSegment("123");
var application = ProductObjectMother.CreateApplication("Foo");
var productfamily = ProductObjectMother.CreateProductFamily("X99");
Engine i = ProductObjectMother.CreateEngine(platform, productfamily, application, mainsegment);
var repository = new ProductRepository();
repository.Save(i);
repository.Flush();
}
最佳答案
问题似乎出在既没有使用 _transactionScope.Complete() 提交也没有通过抛出异常回滚的事务上。
我还注意到一件奇怪的事情,测试通常会失败或通过测试中缺少的“断言”函数(断言中的等于、不等于、存在等)成功运行。 :)
关于c# - 为什么 MSDTC 在使用 mstest 进行单元测试时表现不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11968927/