简体   繁体   中英

How do I unit test a Command Handler that returns a void?

Please see the code below:

public class CreatePersonHandler
        : IRequestHandler<CreatePersonCommand,Unit>
    {

 public async Task<Unit> Handle(CreatePersonCommand message, CancellationToken cancellationToken)
        {
            var person = _enquiryFactory.Create(message.Gender, message.Salary);
            var offers = getAvailableOffers(); 
            person.AssignOffers(offers);
            await _mediator.DispatchDomainEventsAsync(person);
            return Unit.Value;
        }
  }

Notice that:

1) The command does not have any state.
2) The command method has no return value.

I have read a few similar questions on here eg this one: Unit testing void methods? . Are CQRS command handlers that return voids classed as informational and should not be unit tested?

Fundamentally, testing a "command handler" that returns a void is no different from testing a method that returns a void -- the void return is a clear indication that the method is invoked for its side effects, so you check for those.

Depending on the nature of the subject under test, it may make sense to use a test double , rather than a live collaborator, to determine whether or not the right thing happened.

var person = _enquiryFactory.Create(message.Gender, message.Salary);
var offers = getAvailableOffers(); 
person.AssignOffers(offers);
await _mediator.DispatchDomainEventsAsync(person);
return Unit.Value;

One thing to notice in this example is that, not only is there no state in your handler, but there is also no logic -- any branching here is encapsulated within the collaborators.

Assuming the pieces fit together, there's not a lot that can fail that is the responsibility of the handler. So I wouldn't block a pull request like this because there wasn't a "unit test" for the handler.

Could you clarify what you mean by: "Assuming the pieces fit together". I

In a "strongly typed" language, we would get a lot of checking done for us by the compiler/interpreter. If the type system isn't satisfied, then we are going to get an error message before the method is loaded into the execution environment.

I see that you are adding/raising new events using .DispatchDomainEventsAsync(). Instead of returning nothing, you can return these events and write a simple unit test to count the number or structure these events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM