简体   繁体   English

以lambda表达式作为参数的存储库中的Moq函数

[英]Moq function in repository with a lambda expression as an argument

I'm using Moq. 我正在使用起订量。 I want to mock a repository. 我想模拟一个存储库。 Specifically, I want to mock the Exists function of the repository. 具体来说,我想模拟存储库的Exists功能。 The problem is that the Exist function takes a lambda expression as an argument. 问题在于Exist函数将lambda表达式作为参数。

This is a method in my business object that uses the repository. 这是我的业务对象中使用存储库的方法。

    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);
    }

This is what I have now for my test: 这是我现在要进行的测试:

    [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);
    }

How do I mock Exists()? 如何模拟Exists()?

You're not telling explicitly whether your lambda is a Func<Vendor, bool> or an Expression<Func<Vendor, bool>> . 您没有明确告诉您的lambda是Func<Vendor, bool>还是Expression<Func<Vendor, bool>> I'll assume you mean Func<Vendor, bool> here, but if you don't then just replace the type accordingly. 我假设您的意思是Func<Vendor, bool> ,但如果您不这样做,则只需相应地替换类型。

I didn't test this, but it should work: 我没有对此进行测试,但是它应该可以工作:

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;
              });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM