Home > Back-end >  How to mock setup for interface Ilogger's Error method?
How to mock setup for interface Ilogger's Error method?

Time:04-27

My Controller's method

public async Task<IActionResult> GetPathData([FromODataUri] string uid)
{
 try
 {
  if (!Guid.TryParse(uid, out Guid requestTypeGuid))
  {
   throw new ArgumentException($"{nameof(requestTypeGuid)} is null");
  }
   ...
   return Ok(response);
 }
 catch (Exception ex)
 {
  _log.Error(ex, ex.Message);
  return BadRequest(ex.Message);
  }
}

my mock setup

public class SomeControllerTest
{
 private MockRepository mockRepository;
 private Mock<ILog> mockLog;
public SomeControllerTest()
{
 this.mockRepository = new MockRepository(MockBehavior.Strict);
 this.mockLog = this.mockRepository.Create<ILog>();
}
private SomeController CreateSomeController()
{
 return new SomeController(this.mockLog.Object);
}

my unit test case

[Fact]
public async Task GetPathData_IfBlock_ArgumentException()
{
 // Arrange
 var someController = this.CreateSomeController();
 mockLog.Setup(x => x.Error(It.IsAny<string>())); //I tried this
 //Act
 var result = await someController.GetPathData("2");
 //Assert
 var ex = Assert.Throws<ArgumentException>(() => result);
 Assert.Equal("requestTypeGuid is null", ex.Message);
}

getting error : Message:

Moq.MockException : ILog.Error(System.ArgumentException: requestTypeGuid is null at TMo.MWav.API.Controllers.SomeController.GetPathData(String uid) "requestTypeGuid is null") invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup.

CodePudding user response:

If you use MockBehavior.Strict, you should set up ALL invocations.

Fou your use case:

public async Task<IActionResult> GetPathData([FromODataUri] string uid)
{
    // ...
    catch (Exception ex)
    {
        _log.Error(ex, ex.Message);
        // invoke ILog.Error with two parameters: `Exception` and `string`
    }
    // ...
}

, the test should be set up like this:

public async Task GetPathData_IfBlock_ArgumentException()
{
    // ...
    mockLog.Setup(x => x.Error(It.IsAny<Exception>(), It.IsAny<string>()));

    // ...
}

Maybe you can use the test to check your method behavior:

[Fact]
public async Task GetPathData_IfBlock_ArgumentException()
{
    // Arrange
    var expectedMsg = "requestTypeGuid is null";
    var someController = this.CreateSomeController();
    mockLog.Setup(x => x.Error(It.IsAny<Exception>(), It.IsAny<string>()));

    //Act
    var result = await someController.GetPathData("2");

    //Assert
    Assert.IsType<BadRequestObjectResult>(result);
    Assert.Equal(expectedMsg, (result as BadRequestObjectResult)?.Value);
    mockLog.Verify(
        x => x.Error(It.IsAny<ArgumentException>(), expectedMsg),
        Times.Once);
}
  • Related