mercredi 3 février 2021

Advice on testing MediatR controllers and handlers

I have a very subjective question, and I would like some opinions. I know there is no right answer, and sorry if this is against the rules, but I'm posting it because it may help others.

In my project, 99% of the controllers follow the following model:

    [HttpPost]
    [Route("filter")]
    public async Task<ActionResult<MyDTO>> Filter([FromBody] MyCommand data)
    {
        var result = await Mediator.Send(data);

        return HttpResponse(result);
    }

I receive an object that is a command class and this object is then sent to Mediator. The response is sent to the HttpResponse method in my BaseController, and this method is responsible for interpreting the Mediator answer and return 200, 400, 500, etc and map the response to a DTO when needed.

The BaseController has its own tests, so is there any reason/advantage of testing these controllers? I see that if I do that, I'm just testing the MediatR library and I can not see the point of it.

Now let's talk about the MediatR handlers. Some of my handlers have a little bit of logic, so I really need to test them. But some other handlers work only as a shortcut to a given service, like this:

MediatR handler

    public class Handler : BaseQueryHandler<Command>
    {
        private readonly IAnalyticModuleStore _context;

        public Handler(IHttpContextAccessor httpContextAccessor, IAnalyticModuleStore context)
            : base(httpContextAccessor)
        {
            _context = context;
        }

        protected override async Task<object> ExecuteAsync(Command request)
        {
            return await _context.FilterAsync(request.DateFrom, request.DateTo, request.Versions, request.Areas, request.Domains, request.Actions,
                request.Users, request.Agents, request.Responses, null, request.Duration, request.EntityId);
        }
    }

Don't worry about the BaseQueryHandler, it is properly tested.

This is how I would write a test for this handler: mock the IAnalyticModuleStore service and the FilterAsync method, then create a command and send it to the handler to assert the response values.

But assuming that the IAnalyticModuleStore.FilterAsync method is properly tested, in the end, what I'm testing is a fake object. Is there any readon/advantage of testing these heandlers?

Aucun commentaire:

Enregistrer un commentaire