Unit test for controller doesn't work as expected
Solution 1:
The answer was supplied by Chetan in the comments:
I think you need to cast to
NotFoundResult
instead ofNotFoundObjectResult
You're not passing an object in return NotFound()
so you should use NotFoundResult
instead. The As
operator is returning null which is why you're getting the exception. Update the Assert to:
Assert.Equal(StatusCodes.Status404NotFound, (result as NotFoundResult).StatusCode);
This was tested and is working for me using your original setup with this:
_mediator.Setup(x => x.Send(It.IsAny<GetMForProvQuery>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(() => null);
Original answer before you clarified you're using optional parameters
Are you sure you're setting up the correct overload for _mediator.Send
? It looks like you're setting up a different overload for Send
in:
_mediator.Setup(x => x.Send(It.IsAny<GetMForProvQuery>(), It.IsAny<CancellationToken>()))...
which takes 2 parameters. However, you're calling it with a single argument in the controller:
var result = await _mediator.Send(new GetMForProvQuery() { ProvId = provId })
Could you try setting up the single argument overload and pass an action returning null:
_mediator.Setup(x => x.Send(It.IsAny<GetMForProvQuery>()))
.ReturnsAsync(() => null);