I am currently writing unit tests for a CommandHandler. I use Moq 4.12.0 and xUnit 2.4.1 for the tests. I wanted to verify whether that a method was called with a certain NSpecification.
I'm pretty new in the unit-testing world.
This is the CommandHandler:
public class DeleteAlarmCodesCommandHandler : IRequestHandler<DeleteAlarmCodesCommand, CommandResult<IEnumerable<AlarmCode>>>
{
private readonly Domain.Model.IAlarmCodeRepository _alarmCodeRepository;
public DeleteAlarmCodesCommandHandler(
Domain.Model.IAlarmCodeRepository alarmCodeRepository)
{
_alarmCodeRepository = alarmCodeRepository;
}
public async Task<CommandResult<IEnumerable<AlarmCode>>> Handle(DeleteAlarmCodesCommand request, CancellationToken cancellationToken)
{
ASpec<Domain.Model.AlarmCode> spec = Spec<Domain.Model.AlarmCode>.Any;
if (request.AlarmId != null)
{
spec &= Domain.Model.AlarmCodeSpecifications.ForAlarmId(request.AlarmId);
}
if (request.LanguageISO != null)
{
spec &= Domain.Model.AlarmCodeSpecifications.ForLanguageISO(request.LanguageISO);
}
try
{
var alarmCodes = await _alarmCodeRepository.DeleteAsync(spec);
await _alarmCodeRepository.SaveAsync();
return new CommandResult<IEnumerable<AlarmCode>>(alarmCodes.Select(x => x.ToViewModel()));
}
catch (Domain.ApiDomainException ex)
{
return new CommandResult<IEnumerable<AlarmCode>>(ApiErrors.FromException(ex));
}
}
}
And this is my unit test to check whether the DeleteAsync() is called with the specification.
[Fact]
public async Task Should_DeleteWithAlarmIdOne_WhenCalledWitParameterAlarmIdOne()
{
// Arrange
var repo = new Mock<IAlarmCodeRepository>();
var command = new DeleteAlarmCodesCommand() { AlarmId = 1 };
var commandHandler = new DeleteAlarmCodesCommandHandler(repo.Object);
// Act
var result = await commandHandler.Handle(command, It.IsAny<CancellationToken>());
var spec = Spec<AlarmCode>.Any & AlarmCodeSpecifications.ForAlarmId(command.AlarmId);
// Assert
repo.Verify(x => x.DeleteAsync(spec), Times.Once);
repo.Verify(x => x.SaveAsync(), Times.Once);
}
The problem is that the reference to both objects are different, as they are created when they are needed. So Moq sees them as completely different objects. Because when I run the test, I get the following result in the result pane.
Duration: 182 ms
Message:
Moq.MockException :
Expected invocation on the mock once, but was 0 times: x => x.DeleteAsync(x => (True AndAlso (Convert(Convert(x.AlarmId, Int32), Nullable`1) == Convert(value(Services.Domain.Model.AlarmCodeSpecifications+<>c__DisplayClass0_0).alarmId, Nullable`1))))
Performed invocations:
Mock<IAlarmCodeRepository:1> (x):
IAlarmCodeRepository.DeleteAsync(x => (True AndAlso (Convert(Convert(x.AlarmId, Int32), Nullable`1) == Convert(value(Services.Domain.Model.AlarmCodeSpecifications+<>c__DisplayClass0_0).alarmId, Nullable`1))))
IRepository`1.SaveAsync()
Stack Trace:
Mock.Verify(Mock mock, LambdaExpression expression, Times times, String failMessage)
Mock`1.Verify[TResult](Expression`1 expression, Func`1 times)
DeleteAlarmCodesCommandHandler_Handle.Should_DeleteWithAlarmIdOne_WhenCalledWitParameterAlarmIdOne() line 46
--- End of stack trace from previous location where exception was thrown ---
Is there a way with Moq to verify calls with complex objects, like the Spec.
Or how can I test this better?
Update
This is the definition of IAlarmCodeRepository.
public interface IAlarmCodeRepository : IRepository<AlarmCode>
{
IUnitOfWork UnitOfWork { get; }
Task AddAsync(AlarmCode entity);
Task<AlarmCode> GetOneAsync(int id);
Task<AlarmCode> GetOneAsync(ASpec<AlarmCode> spec);
Task<IEnumerable<AlarmCode>> FindAsync(ASpec<AlarmCode> spec);
Task<bool> Exists(ASpec<AlarmCode> spec);
Task<IEnumerable<AlarmCode>> DeleteAsync(ASpec<AlarmCode> spec);
Task<AlarmCode> DeleteOne(int id);
Task<IEnumerable<short>> GetDistinctAlarmIds();
}
public interface IRepository<T>
where T : IAggregateRoot
{
Task SaveAsync();
}
public async Task SaveAsync()
{
await UnitOfWork.CommitAsync();
}
This are the AlarmSpecifications.
public static class AlarmCodeSpecifications
{
public static ASpec<AlarmCode> ForAlarmId(short? alarmId)
{
return new Spec<AlarmCode>(o => o.AlarmId == alarmId);
}
}
Spec and ASpec comes from the NSpecifications library on https://github.com/jnicolau/NSpecifications : https://github.com/jnicolau/NSpecifications/blob/master/Nspecifications/ASpec.cs