0

I'm trying to setup unit testing for my API controllers. I'm using the mediatr pattern and FakeIteasy. I have the following code.

public class ChannelGroupChannelsControllerTests
{
    private readonly ChannelGroupChannelsController _controller;
    private readonly IMediator _mediator;

    public ChannelGroupChannelsControllerTests()
    {
        var service = A.Fake<IReadChannelGroupChannel>();
        var mapper = A.Fake<IMapper>();

        var channelGroupChannel = new ChannelGroupChannel
        {
            Id = 1,
            ChannelGroupId = 1,
            ChannelId = 1,
            Channel = new Channel { Name = "Channel Name" }
        };

        _mediator = A.Fake<IMediator>();
        _controller = new ChannelGroupChannelsController(_mediator, mapper);

        A.CallTo(() => _mediator.Send(A<GetChannelGroupChannelById>._, A<CancellationToken>._)).Returns(channelGroupChannel);
    }


    [Fact]
    public async Task ChannelGroupChannelsController_ById()
    {
        var result = await _controller.ById(1);

        (result.Result as StatusCodeResult)?.StatusCode.Should().Be((int)HttpStatusCode.OK);
        result.Value.Should().BeOfType<ChannelGroupChannelVM>();
    }
}

Now the problem is that I keep getting NULL as a value. I think the issue might be that GetChannelGroupChannelById has a constructor that expects the ID. But I'm not sure...

Does anybody know what could be wrong? I'm pretty new with the mocking stuff.

Kind regards

Nkosi
  • 235,767
  • 35
  • 427
  • 472

1 Answers1

0

I'm not familiar with mediatr, so may be off base here, and it would be much easier to answer this question if we saw what your controller was doing. If you're able, please supply the code, as without that insight, I'm left to guess a little, but I'll try.

If GetChannelGroupChannelById's constructor expects an ID (an int?), FakeItEasy will provide an ID when it makes the Fake version. If it's an int, FakeItEasy will provide a 0, unless you've done some very fancy configuration you've not shown us. If that's supposed to line up with some other value in your code and doesn't, it may cause your problem.

Otherwise, I see you have a Fake IMapper, that is never configured, but is passed into the controller. I'm guessing this is supposed to translate some values. An unconfigured Fake will return a dummy value (or default if no dummy value can be made). It's possible that this unconfigured mapper is interrupting your flow.

(I also see that service in the test class constructor is unused. I would remove it or use it. It may not be part of your problem, but it's at least distracting.)

Blair Conrad
  • 233,004
  • 25
  • 132
  • 111
  • 1
    In my controller is following code var request = new GetChannelGroupChannelById(id); var channelGroupChannel = await _mediator.Send(request); return Ok(_mapper.Map(channelGroupChannel)); Thanks for the help. – Evert Dausy Jul 03 '20 at 10:37