Search code examples
c#moqxunit

How to get Mock to return null if setup isn't exactly matched


I'm trying to test a function and I want a mock to return a null if the setup isn't matched exactly. But it's returning a 'mocked' object; an object with default values. I've tried setting the mock.SetReturnsDefault to null and mock.DefaultValue = null, with no change.

[Theory]
[InlineData("DFF0DF04-0D3F-419B-82FB-23F0A8E2452C", 1)]
[InlineData("DFF0DF04-0D3F-419B-82FB-23F0A8E2452C", 2)]
[InlineData("985F7161-1B0F-4EEA-9572-02D6D13D712B", 1)]
public async Task Get_ShouldReturn1TierSet_GivenAProgram_And_AnExistingId(Guid programId, int id)
{
    _tierSetService.Setup(x => x.GetTierSet(1, new Guid("DFF0DF04-0D3F-419B-82FB-23F0A8E2452C"))).ReturnsAsync(new TierSet()
    {
        Id = 1,
        StartDate = DateTime.Now,
        EndDate = DateTime.Now,
        Name = "Some Tier Set",
        TierSetState = Core.Constants.TierSetState.Draft,
        CreateDate = DateTime.Now,
        Program = new Domain.Models.Program(){ },
        DisplayTierSet = false
    });

    var actual = await _controller.Get(programId, id);
    if (programId == new Guid("DFF0DF04-0D3F-419B-82FB-23F0A8E2452C") && id == 1)
    {
        Assert.NotNull(actual);
    }
    else
    {
        Assert.Null(actual);
    }
}

I added another test and set up the mock to return null with It.IsAny<>() arguments, and that works as expected. Any reason it wouldn't return null or how to guarantee it will return null if the setup isn't matched?


Solution

  • Just so that we can close this question here. OP mentioned that the suggestions I provided in the comments resolved his issue. Adding this post here and for anyone looking for an answer about similar behavior, the solution is to set multiple setups on your Mock object to return the expected value. Example

        _tierSetService.Setup(x => x.GetTierSet(1, It.IsAny<Guid>))).ReturnsAsync(new TierSet()
        {
            Id = 1
        });
    
        _tierSetService.Setup(x => x.GetTierSet(2, It.IsAny<Guid>()))).ReturnsAsync(null));
    

    So this way when the proxy calls the _tierSetService.GetTierSet with the matching "arguments", will try to match the correct fake and return the same.