1

There is such a method for getting some data from the database:

public async Task<T> GetByFilter(Func<IQueryable<T>, IQueryable<T>>? queryModifier, CancellationToken cancellationToken = default)
{
    try
    {
        using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(GET_BY_FILTER_AWAITING));
        cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cts.Token).Token;

        IQueryable<T> query = _dbSet;

        if (queryModifier is not null)
            query = queryModifier(query);

        return await query.FirstOrDefaultAsync(cancellationToken);
    }
    catch (OperationCanceledException)
    {
        throw new OperationCanceledException(REQUEST_TIMED_OUT);
    }
    catch (Exception ex)
    {
        _logger.LogCritical(ex.ToString(), nameof(_context), nameof(_dbSet));
        throw new OperationCanceledException(Message.ERROR);
    }
}

It takes as a parameter a modification delegate of an existing LINQ query:

Func<IQueryable<T>, IQueryable<T>>? queryModifier

Next, in the method that needs to be tested, this function is used to receive the user by his email:

var user = await userRepository.GetByFilter(query => query.Where(u => u.email.Equals(email.ToLowerInvariant())));

Here is the complete code of the method that needs to be tested:

public async Task<IActionResult> RecoveryAccount([FromQuery] string email)
{
    try
    {
        var user = await userRepository.GetByFilter(query => query.Where(u => u.email.Equals(email.ToLowerInvariant())));
        if (user is null)
            return StatusCode(404, new { message = Message.NOT_FOUND });

        string token = Guid.NewGuid().ToString("N") + Guid.NewGuid().ToString() + generate.GenerateKey();
        await recoveryHelper.CreateTokenTransaction(user, token);
        await emailSender.SendMessage(new EmailDto
        {
            username = user.username,
            email = email,
            subject = EmailMessage.RecoveryAccountHeader,
            message = EmailMessage.RecoveryAccountBody + $"{fileManager.GetReactAppUrl()}/auth/recovery?token={token}"
        });

        await redisCache.DeteteCacheByKeyPattern($"{ImmutableData.NOTIFICATIONS_PREFIX}{user.id}");

        return StatusCode(201, new { message = Message.EMAIL_SENT });
    }
    // Handling some exceptions, doesn't make sense to specify in the question
    catch (Exception ex)
    {
        return StatusCode(500, new { message = ex.Message });
    }
}

When testing, I need to mock the call to this method with a specific Func<IQueryable, IQueryable>

I do it like this:

// Creating Mock Object UserRepository:
var userRepositoryMock = new Mock<IRepository<UserModel»();

// Creating specific Func
Func<IQueryable<UserModel>, IQueryable<UserModel» query = query => query.Where(u => u.email.Equals(email.ToLowerInvariant()));

// Mock my method with my Func
userRepositoryMock.Setup(x => x.GetByFilter(query, CancellationToken.None))
    .ReturnsAsync(user);

But as a result of the mock, I do not get the user object that was expected: .ReturnsAsync(user), but null

I assume that this is because references to delegates are compared, and not the values ​​of delegates, so there is no coincidence, I don’t understand how to get around this.

I commented out those places that probably do not have much relevance to the question.

Next is the test itself, in which it is necessary to mock a method with a specific Func:

[Fact]
public async Task RecoveryAccount_Success()
{
    var id = 1;
    var email = "[email protected]";
    var username = "air2921";
    Func<IQueryable<UserModel>, IQueryable<UserModel>> query = query => query.Where(u => u.email.Equals(email.ToLowerInvariant()));
    var user = new UserModel
    {
        id = id,
        username = username,
        email = email
    };

    var userRepositoryMock = new Mock<IRepository<UserModel>>();
    //var generateMock = new Mock<IGenerate>();
    //var emailSenderMock = new Mock<IEmailSender>();
    //var redisCacheMock = new Mock<IRedisCache>();
    //var fileManagerMock = new Mock<IFileManager>();
    //var recoveryServiceMock = new Mock<IRecoveryHelpers>();

    userRepositoryMock.Setup(x => x.GetByFilter(query, CancellationToken.None))
        .ReturnsAsync(user);
    //generateMock.Setup(x => x.GenerateKey()).Returns("8ifrnDa8a9nabJDfjTrfXsgfVIhCYGrZbN5HdtX0dK8=");
    //fileManagerMock.Setup(x => x.GetReactAppUrl()).Returns(string.Empty);

    var recoveryController = new RecoveryController(/*recoveryServiceMock.Object, null,*/ userRepositoryMock.Object/*,*/
        /*null, emailSenderMock.Object, redisCacheMock.Object, fileManagerMock.Object, generateMock.Object*/);

    var result = await recoveryController.RecoveryAccount(email);

    Assert.IsType<ObjectResult>(result);
    var objectResult = (ObjectResult)result;
    Assert.Equal(201, objectResult.StatusCode);

    //recoveryServiceMock.Verify(x => x.CreateTokenTransaction(user, It.Is<string>(q => q.Length >= 112)), Times.Once);
    //emailSenderMock.Verify(x => x.SendMessage(It.Is<EmailDto>(e => e.username == username && e.email == email)), Times.Once);
    //redisCacheMock.Verify(x => x.DeteteCacheByKeyPattern($"{ImmutableData.NOTIFICATIONS_PREFIX}{id}"), Times.Once);
}
2
  • 1
    Your assumption regarding delegate equality is correct. One way is to create an actual method with the required signature, if you have the same method as delegate, the comparison would work. Another way would be to write two seperate unit tests. One would simply return the mock user for any delegate. And the other test simply captures the passed delegate, invokes it on a queryable and tests if the query behaves correctly for a given data set.
    – DevMoth
    Commented Apr 3 at 9:43
  • @DevMoth Thank you, the option of capturing the passed delegate gave me an idea that helped me solve the problem, although it seems to me that this is a bit of a crutch. But I don’t have time to figure it out, thank you very much.
    – air
    Commented Apr 3 at 13:24

1 Answer 1

0

My recommendation would be to just create a custom class for mocking your repository. Something like a MemoryRepository that uses a list or dictionary as the backing storage, but otherwise fulfill the interface of IRepository.

When writing unit tests you should test the 'interface' of a method. If your test is just a list of things the method should call your test will likely be fragile, and any change in implementation is likely to break your tests. Providing a more complete implementation of dependencies may help to avoid some of this fragility.

Not that mocking frameworks are in any way bad. But they may not be the best tool for all kinds of mocking.

Do note that it can be difficult to reproduce the behavior of a database correctly. Not all queries that compile are possible to translate to SQL, and some behavior will depend on the database engine used. The EF In-memory database might be useful for some kinds of tests. Using an actual instance of your database can be useful for other tests, where correctness is more important than things like runtime.

2
  • There is nothing wrong with mocking repository like what OP did. The whole point of a repository in terms of testing is to avoid interaction with a database. It's also one of the official recommended approaches to test EF
    – quyentho
    Commented Apr 7 at 6:56
  • @quyentho I am recommending mocking the repository, just not using a mocking framework for more complex mocking tasks. But if your subject under test contains query code, like the OPs does, it is a really good idea to test it against a real-ish database. Otherwise you risk SQL translation errors, and these will not be caught by either a compiler or simple mocked repository. Normally, queries are isolated to the repository, so you test the repository against the real db, and the rest of the code against a mock repo.
    – JonasH
    Commented Apr 8 at 6:33

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.