2

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

1 Answer 1

5

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;
              });
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer. This does work to simulate Exists() returning true but it doesn't help me test my business object correctly since the condition for Exists is not really being checked. Maybe I asked the wrong question. I need to be able to check the Validate method in the BO regardless of how the expression used in the call to Exists() changes. Maybe I need to rewrite part of the BO but I'm not sure how.
I think you should test the two real objects together in the same unit test here, as they're logically linked. That's the most straightforward way.
What if a specific lambda expression is needed instead of It.IsAny<>?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.