Home > OS >  Moq; Unit Test - Method is always failing. ISetup is not working
Moq; Unit Test - Method is always failing. ISetup is not working

Time:11-20

The test method is always failing. After the Setup the method UpdateAsync should return 1 in the result but it remains always 0 which results in exception in the controller method.

Can you tell what I am missing here ?

[Test]
public async Task UpdateImportHeaderAsyncTest()
{
    //Arrange
    HeaderRequest request = new HeaderRequest()
    {
        ConfigurationId = 1,
        Key = "1",
        Status = 1
    };
    _manager.Setup(a => a.UpdateAsync(_mockData.Header)).Returns(Task.FromResult(1));

    //Act
    var actual = await Controller.UpdateHeaderAsync(request);

    //Assert
    Assert.NotNull(actual);
}
//Controller Method
[HttpPut]
public async Task<int> UpdateHeaderAsync(HeaderRequest request)
{
    var result = 0;
    try
    {
        result = await _manager.UpdateAsync(new Header() 
        { 
          HeaderId = request.Id, 
          Status = request.Status, 
          ConfigurationId = request.ConfigurationId 
        });

        if (result == 0)
        {
            throw new RecordNotFoundException("No records found.", "1", "");
        }
    }
    catch (Exception ex)
    {      
        throw;
    }
    return result;
}

CodePudding user response:

Loosen the argument match using It.IsAny<Header>()to get the desired behavior.

//...

_manager
    .Setup(a => a.UpdateAsync(It.IsAny<Header>()))
    .ReturnsAsync(1);

//...

The setup also allows for ReturnsAsync for setting up async members.

What was happening before was that you were setting it up with a specific referenced instance. That instance was not the same one used when exercising the test since you initialized a new Header. This caused the mock to return the default value for the return type.

Reference Moq Quickstart to get a better understanding of how to use the framework

  • Related