在 rhino 模拟中模拟 lambda
我正在尝试使用 Rhino Mocks 来模拟以下 lambda,但一直碰壁
var result = rep.Find<T>(x => (x as IEntity).ID == (entity as IEntity).ID).FirstOrDefault();
有什么想法吗?
I am trying to use Rhino Mocks to mock the following lambda, but keep hitting a brick wall
var result = rep.Find<T>(x => (x as IEntity).ID == (entity as IEntity).ID).FirstOrDefault();
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在单元测试中,您拥有被测系统 (SUT) 及其协作者。模拟的目标是用您可以完全控制的东西取代协作者。这样您就可以设置不同的测试用例,并且可以专注于测试被测系统的行为,而不是其他任何事情。
在本例中,我假设
rep
对象是 SUT。您传递给 SUT 的 Find 方法的 lambda 可以被视为协作者。由于您已经完全控制了该 lambda,因此尝试使用 Rhino Mocks 来模拟它并没有多大意义。无论如何,我将尝试给出一个涉及 Rhino Mocks 和 lambda 的单元测试示例;-) 这是一个示例测试,它创建一个始终返回 false 的谓词存根,并验证
Find
方法实际上调用了该谓词:当然,正如在您自己的示例中一样,您在这里并不真正需要 Rhino Mocks。 lambda 语法的全部要点是让就地提供实现变得容易:
In a unit test, you have the system under test (SUT) and its collaborators. The goal of mocking is to replace the collaborators by something that you have full control over. That way you can set up different test cases and you can focus on testing just the behavior of the system under test, and nothing else.
In this case, I assume the
rep
object is the SUT. The lambda that you pass to the SUT'sFind
method could be considered a collaborator. Since you already have full control over that lambda, it doesn't really make sense to try to mock it with Rhino Mocks.I'll try to give an example of unit test involving Rhino Mocks and lambdas anyway ;-) This is an example test which creates a predicate stub that always returns false, and which verifies that the
Find
method actually invoked that predicate:Of course, as in your own example, you don't really need Rhino Mocks here. The whole point of the lambda syntax is to make it easy to provide an implementation in-place:
找到了我想要的答案
Found the answer I was after
这样我们就无法出来..因为由于 IgnoreArguments(),它永远不会进入内部并看到参数的值,而我们将通过。
但这种方法的主要问题是编写 AssertWasCalled(某些 lambda 表达式)是不可能的,因为现在在 Assert 部分中它显示错误,例如 ExpectaionViolationException 未被用户代码处理
this way we can't come out..because due to the IgnoreArguments(),it will never go inside and see the value of arguments and we will pass through.
But the major problem with this approach is writing the AssertWasCalled(some lambda expression) is not possible because now in the Assert part it is showing error like ExpectaionViolationException was unhandled by user code