Lambda表达式比较
我正在使用机器规范进行测试,有一些我无法做到的事情,想知道以前是否有人去过那里,
有没有办法使用 Rhino Mocks 为使用 lambda 的方法创建存根表达式,我发现我可以执行以下操作
在示例类中包含此方法:
public void UpdateVisit(int userId){
var user = repository.FindBy<User>(x=>x.Id==userId && user.IsActive ==true);
user.Visit = user.Visit + 1;
repository.Save(user);
}
我可以像这样存根该方法:
//...Inside test method
var user = new User();
repository.Stub(x=>x.FindBy<User>(Arg<Expression<Func<User,bool>>>.Is.Anything)).Return(user);
问题是我想将该方法存根到任何 Lambda 表达式,只是对于特定的 lambda 表达式 “x=>x.Id==userId && user.IsActive ==true”
,这样测试就会失败方法中的表达式更改...
我想我可以创建一个不访问数据库的模拟存储库并测试 lambda 中的行为,尽管如此,我想知道是否有另一种方法...
感谢任何建议这, 谢谢
I was playing around with testing using machine specifications and there is something that i am just not able to do, was wondering if somebody have been there before,
Is there any way to using Rhino Mocks to create a stub for a method that uses a lambda expression, i found that i can do the following
Having this method in a sample class:
public void UpdateVisit(int userId){
var user = repository.FindBy<User>(x=>x.Id==userId && user.IsActive ==true);
user.Visit = user.Visit + 1;
repository.Save(user);
}
I can stub the method like this:
//...Inside test method
var user = new User();
repository.Stub(x=>x.FindBy<User>(Arg<Expression<Func<User,bool>>>.Is.Anything)).Return(user);
The thing is I would like to stub the method not to Any Lambda Expression, just for the specific lambda expression "x=>x.Id==userId && user.IsActive ==true"
, so that the test would fail if this expression changes in the method...
I guess i could create a mock repository that does not go to the database and test the behavior in the lambda though this, i was wondering if there is another approach to this...
Appreciate any suggestions on this,
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不想测试方法中是否使用了特定的 lambda 表达式。您想要测试该方法应该具有的行为。测试特定 lambda 表达式等实现细节通常太脆弱。反而:
You don't want to test that the particular lambda expression is used in the method. You want to test the behavior that the method is suppose to have. Testing implementation details like a specific lambda expression is in general too brittle. Instead: