如何模拟接口 Ilogger 的错误方法的设置?

How to mock setup for interface Ilogger's Error 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);
  }
}

我的模拟设置

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

我的单元测试用例

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

获取错误:消息:

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.

如果您使用 MockBehavior.Strict,您应该设置所有调用。

了解您的用例:

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`
    }
    // ...
}

,测试应该这样设置:

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

    // ...
}

也许您可以使用测试来检查您的方法行为:

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