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