Home > Software design >  Moq testing repositories
Moq testing repositories

Time:06-30

Trying to moq a repository call.

public async Task<T> GetFirstOrDefault<T>(Expression<Func<T, bool>> predicate) where T : class
{
    return await WithQuery<T, T>(q => q.FirstOrDefaultAsync(predicate));
}

Then in my unit testing:

var ruleList = new List<Rule>() (Imagine my list here)

_mockRepository.Setup(x => x.GetFirstOrDefault<Rule>(x => It.IsAny<string>() == It.IsAny<string>())).ReturnsAsync(ruleList);

This always returns null when it goes into my code. I have a similar call not using a predicate that will return the value, it looks like this:

public Task<IEnumerable<T>> ListAll<T>() where T : class
{
    return WithQuery<T, IEnumerable<T>>(async q => await q.ToListAsync());
}

and

var ruleList = new List<Rule>() (Imagine my list here)

_mockRepository.Setup(x => x.ListAll<Rule>()).ReturnsAsync(ruleList);

This is not null. I'm probably missing something simple at this point but I have tried a few things without luck.

Edit: thanks to Nkosi for the explanation and with a slight modification I was able to do:

_mockRepository.Setup(_ => _.GetFirstOrDefault<Rule>(It.IsAny<Expression<Func<Rule, bool>>>()))
    .Returns((Expression<Func<Rule, bool>> predicate) => {
        return Task.FromResult<Rule>(ruleList);
    });

CodePudding user response:

The expression in the setup predicate is trying to use It.IsAny as a parameter in the expression. That is why it is failing.

If the goal is to try to replicate the expected behavior using the list as a data source then review the following setup example

_mockRepository
    .Setup(_ => _.GetFirstOrDefault<Rule>(It.IsAny<Expression<Func<Rule, bool>>>()))
    .Returns((Expression<Func<Rule, bool>> predicate) => {
        Rule result = ruleList.FirstOrDefault(predicate);
        return Task.FromResult<Rule>(result);
    });
    

The expression argument is captured and applied to the list using LINQ

  • Related