Vic*_*r P 2 c# lambda unit-testing moq
我正在使用Moq.我想模拟一个存储库.具体来说,我想模拟存储库的Exists功能.问题是Exist函数将lambda表达式作为参数.
这是我的业务对象中使用存储库的方法.
public override bool Validate(Vendor entity)
{
// check for duplicate entity
if (Vendors.Exists(v => v.VendorName == entity.VendorName && v.Id != entity.Id))
throw new ApplicationException("A vendor with that name already exists");
return base.Validate(entity);
}
Run Code Online (Sandbox Code Playgroud)
这就是我现在测试的内容:
[TestMethod]
public void Vendor_DuplicateCheck()
{
var fixture = new Fixture();
var vendors = fixture.CreateMany<Vendor>();
var repoVendor = new Mock<IVendorRepository>();
// this is where I'm stuck
repoWashVendor.Setup(o => o.Exists(/* what? */)).Returns(/* what */);
var vendor = vendors.First();
var boVendor = new VendorBO(repoVendor);
boVendor.Add(vendor);
}
Run Code Online (Sandbox Code Playgroud)
我如何模拟Exists()?
你没有明确告诉你的lambda是a Func<Vendor, bool>还是a Expression<Func<Vendor, bool>>.我假设你的意思是Func<Vendor, bool>在这里,但如果你不这样做,那么只需更换类型.
我没有测试这个,但它应该工作:
repoWashVendor.Setup(o => o.Exists(It.IsAny<Func<Vendor, bool>>))
.Returns((Func<Vendor, bool> predicate) => {
// You can use predicate here if you need to
return true;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2146 次 |
| 最近记录: |