Moq和Transactionscope,你能让moqs不算数吗?
当我使用未提交的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想到了一些策略。
Commit
。我不推荐这个。这将是一个仅用于测试的毫无意义的抽象,因为真正的数据库类(可能)在幕后做同样的事情。它将等待调用数据库,直到调用
Commit
。Commit
未被调用。您想要做的是有状态测试 - 您正在根据
Commit
和的方式验证这些调用的状态回滚会影响它们。这不是使用模拟的正确方法。
如果您验证未调用
Commit
,则您正在测试回滚事务的代码的高级行为及其与数据库类的交互。您验证是否调用了回滚,并且未调用提交,并相信它将正确处理详细信息。类似于:
如果您需要验证数据库类本身,您可以模拟其数据库连接,并验证在调用
Rollback
时不会进行调用。但是除非您直接对该数据库类进行单元测试,否则您不应该进行此类测试。A couple strategies come to mind.
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.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
andRollback
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:
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.