Moq和Transactionscope,你能让moqs不算数吗?

发布于 2024-10-16 01:30:55 字数 421 浏览 1 评论 0原文

当我使用未提交的 Transactionscope 时,起订量仍然会看到对数据库的所有回滚调用。

有没有办法

_mockRepository.Verify(x => x.InsertSBI(It.IsAny<Int32>(), It.IsAny<Int32>(), It.IsAny<String>()), Times.Never());

_mockRepository.Verify(x => x.InsertSBI(It.IsAny<Int32>(), It.IsAny<Int32>(), It.IsAny<String>()), Times.Exactly(4));

让测试不成功

When i'm using a Transactionscope that i don't commmit, moq still sees all the rolled back calls to the database.

Is there a way of doing

_mockRepository.Verify(x => x.InsertSBI(It.IsAny<Int32>(), It.IsAny<Int32>(), It.IsAny<String>()), Times.Never());

And not

_mockRepository.Verify(x => x.InsertSBI(It.IsAny<Int32>(), It.IsAny<Int32>(), It.IsAny<String>()), Times.Exactly(4));

to make the test succeed?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眸中客 2024-10-23 01:30:55

我想到了一些策略。

  • 为现有的数据库访问类创建一个包装类。让该包装器等待将任何调用转发到底层实现,直到您调用 Commit

我不推荐这个。这将是一个仅用于测试的毫无意义的抽象,因为真正的数据库类(可能)在幕后做同样的事情。它将等待调用数据库,直到调用Commit

  • 不要尝试以这种方式验证数据访问。相反,验证Commit未被调用

您想要做的是有状态测试 - 您正在根据Commit的方式验证这些调用的状态回滚会影响它们。这不是使用模拟的正确方法。

如果您验证未调用 Commit,则您正在测试回滚事务的代码的高级行为及其与数据库类的交互。您验证是否调用了回滚,并且未调用提交,并相信它将正确处理详细信息。

类似于:

_mockRepository.Verify(x => x.Commit(), Times.Never());
_mockRepository.Verify(x => x.Rollback(), Times.Once());

如果您需要验证数据库类本身,您可以模拟其数据库连接,并验证在调用 Rollback 时不会进行调用。但是除非您直接对该数据库类进行单元测试,否则您不应该进行此类测试。

A couple strategies come to mind.

  • Create a wrapper class for your existing DB access class. Make that wrapper wait to forward any calls to the underlying implementation until you call Commit.

I don't recommend this. It would be a pointless abstraction reserved only for test, because the real DB class (probably) does the same thing under the covers. It will wait to call the DB until Commit is called.

  • Don't try to validate data access this way. Instead validate that Commit wasn't called.

What you're trying to do is stateful testing - you're validating the state of those calls, based on how Commit and Rollback effect them. This is not the right way to go about using mocks.

If you validate that Commit wasn't called, you're testing the high-level behavior of the code that is rolling back the transaction, and its interaction with the DB class. You verify that rollback is called, and that commit isn't called, and trust that it will correctly handle the details.

Something like:

_mockRepository.Verify(x => x.Commit(), Times.Never());
_mockRepository.Verify(x => x.Rollback(), Times.Once());

If you need to verify the DB class itself you can mock out its DB connection and verify that calls don't get made if Rollback is invoked. But you shouldn't do that sort of testing unless you're unit testing that DB class directly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文