Victor P
Victor P

Reputation: 1612

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. The problem is that the Exist function takes a lambda expression as an argument.

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()?

Upvotes: 2

Views: 2828

Answers (1)

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51330

You're not telling explicitly whether your lambda is a Func<Vendor, bool> or an Expression<Func<Vendor, bool>>. I'll assume you mean Func<Vendor, bool> here, but if you don't then just replace the type accordingly.

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

Upvotes: 5

Related Questions