Matt
Matt

Reputation: 2851

Mocking with anonymous parameter

I am trying to Mock my repository layer and I have a method GetSelection(Expression<Func<T, Boolean>> where). I am using Ninjects MickingKernel with Moq to achieve this.

When I do the following, it is fine:

// Create instance of repository
var kernel = new MoqMockingKernel();
var templateRepoMock = kernel.GetMock<ITemplateRepo>();

// Setup mock
templateRepoMock.Setup(x=>x.GetSelection(y=>y.FieldName)
                .Returns(new List<Template>() {new Template { ... })); 
                // Lets pretend that FieldName is a bool!

// Call Service layer
var result = templateService.MyMethod();

// -> Service Layer method
public List<Template> MyMethod() 
{
    return _templateRepo.GetSelection(x=>x.FieldName);
}

But when I try and add an additional parameter within my expression I get an ArgumentNullExeption:

// Setup mock 
templateRepoMock.Setup(x=>x.GetSelection(y=>y.SomeOtherField.Id == 1 
                                         && y.FieldName)
                .Returns(new List<Template>() {new Template { ... }));

When I update my service to the following:

public List<Template> MyMethod(SomeObject myObject) 
{
    return _templateRepo.GetSelection(x=>x.SomeObject.Id == myObject.Id 
                                      && x.FieldName).ToList(); 
}

It appears to be fine if I update myObject.Id to 1.

Any ideas why this could be happening?

Upvotes: 0

Views: 123

Answers (1)

Patrick Quirk
Patrick Quirk

Reputation: 23747

I still don't see the exception that you do, even when using your Github project. Instead, the test fails at the VerifyAll line with this message:

Moq.MockVerificationException : The following setups were not matched:

IProductRepository mock => mock.GetProducts(x => x.Name == "Test" && x.IsActive)

However, I think you may be chasing a red herring, as Moq doesn't support setting up methods that take an Expression. See this answer.

Upvotes: 1

Related Questions