Home > front end >  Unit test for controller doesn't work as expected
Unit test for controller doesn't work as expected

Time:01-19

I have created the following controller:

[HttpGet(“{provId}/m”)]
public async Task<IActionResult> GetMForProv (int provId)
{
   var result = await _mediator.Send(new GetMForProvQuery() { ProvId = provId });

   if (result == null)
   {
      return NotFound();
   }

   return Ok(result);
}

And the following unit test:

public class GetMForProvTest
{
   private readonly ProvController _sut;
   private readonly Mock<IMediator> _mediator;
   private readonly Mock<IConfiguration> _configuration;

   public GetMForProvTest()
   {
      _mediator = new Mock<IMediator>();
      _configuration = new Mock<Iconfiguration>();

      _mediator.Setup(x => x.Send(It.IsAny<GetMForProvQuery>(), It.IsAny<CancellationToken>()))
           .ReturnsAsync(new CatDto());

      _sut = new ProvController(_mediator.Object, _configuration.Object);
   }

   [Fact]
   public async Task ShouldReturnNotFoundResult_AfterGetMForProv()
   {
      var result = await _sut.GetMForProv(123); // this providerId does not exist

      Assert.Equal(StatusCodes.Status404NotFound, (result as NotFoundObjectResult).StatusCode);
   }

When I run the above test, on the line Assert.Equal(…) I get

Object reference not set to an instance of an object.

(… as NotFoundObjectResult returned null.

How can I get this work?

CodePudding user response:

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

CodePudding user response:

Try to fix line:

.ReturnsAsync(new CatDto());

To

.ReturnsAsync((CatDto)null);

Because you return CatDto object and the result of casting (result as NotFoundObjectResult) is null

  •  Tags:  
  • Related