如何对依赖于数据库的WCF存储库进行单元测试,并在测试后进行回滚



我有一些代码在这里检索数据通过linq到SQL从WCF抽象成一个dll。唷。

所以基本上我的测试包括在两个表中创建一些条目,我需要确保表B条目与表A条目有正确的链接。

所以我搜索了一下,发现了之前的讨论,对我来说非常棒的方法是使用事务作用域的方法。

所以我将单元测试修改为:

    [Test, DataRollBack]
    public void TestCreateWarrantNumber_CreateNewWarrant_Return_NewWarrantID()
    {
    string userName = "headauth";
    using (TransactionScope scope = new TransactionScope())
    {
        IdbRepository repository = new dbRepository();
        DataServiceContext db = new DataServiceContext();
        int Id = repository.CreateProduct(Ids, userName);
        var foundId = (from w in db.Transactions
                              where w.Ref == Id.ToString()
                              select w).OrderBy(w => w.Id).FirstOrDefault();
        int foundId = 0;
        if (foundNumberId != null)
        {
            foundId = foundNumberId.Id;
        }
        Assert.AreEqual(Id, foundId,
                        "Transaction must be assigned successfully to the new product.");
    }
}

每次在vs2010中运行此测试时,它都不起作用,并且每次运行此测试时,我可以在数据库中看到此条目都是在产品表上创建的。

所以我认为最简单的测试方法就是将其链接到数据库并以这种方式进行测试,但我现在需要的是如何在每次测试完成时回滚?

我在这里做错了什么有什么想法吗?由于

更新:

启用DTC后,如果不将数据插入表中,我仍然无法进行测试。我尝试了nunitx方法,但也无济于事:(

默认情况下,事务不通过进程边界扩展。您需要在您的服务中启用此功能,然后使用正确的绑定。

在这里你可以找到一些信息。

如果你的WCF服务不支持事务,你不能改变代码,我认为你坚持第二种选择(直接到数据库没有WCF)。然后你的TransactionScope将包括你的数据库更改,并将自动回滚,当你退出范围(因为你没有调用'Commit')

最新更新