如何单元测试 Core MVC 控制器操作是否调用 ControllerBase.Problem()

Mar*_*ijn 6 c# unit-testing core controller-action asp.net-core-mvc

我们有一个控制器,它派生自这样ControllerBase的动作:

public async Task<ActionResult> Get(int id)
{
  try
  {
    // Logic
    return Ok(someReturnValue);
  }
  catch
  {
    return Problem();
  }
}

Run Code Online (Sandbox Code Playgroud)

我们还有这样的单元测试:

[TestMethod]
public async Task GetCallsProblemOnInvalidId()
{
  var result = sut.Get(someInvalidId);

}
Run Code Online (Sandbox Code Playgroud)

但是ControllerBase.Problem()抛出一个空引用异常。这是来自 Core MVC 框架的一个方法,所以我真的不知道它为什么会抛出错误。我认为可能是因为 HttpContext 为空,但我不确定。是否有一种标准化的方法来测试控制器应该调用的测试用例Problem()?任何帮助表示赞赏。如果答案涉及模拟:我们使用 Moq 和 AutoFixtrue。

Nko*_*osi 5

null 异常是因为缺少 ProblemDetailsFactory

在这种情况下,控制器需要能够通过创建ProblemDetails实例

[NonAction]
public virtual ObjectResult Problem(
    string detail = null,
    string instance = null,
    int? statusCode = null,
    string title = null,
    string type = null)
{
    var problemDetails = ProblemDetailsFactory.CreateProblemDetails(
        HttpContext,
        statusCode: statusCode ?? 500,
        title: title,
        type: type,
        detail: detail,
        instance: instance);

    return new ObjectResult(problemDetails)
    {
        StatusCode = problemDetails.Status
    };
}
Run Code Online (Sandbox Code Playgroud)

来源

ProblemDetailsFactory 是一个可设置的属性

public ProblemDetailsFactory ProblemDetailsFactory
{
    get
    {
        if (_problemDetailsFactory == null)
        {
            _problemDetailsFactory = HttpContext?.RequestServices?.GetRequiredService<ProblemDetailsFactory>();
        }

        return _problemDetailsFactory;
    }
    set
    {
        if (value == null)
        {
            throw new ArgumentNullException(nameof(value));
        }

        _problemDetailsFactory = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

来源

在单独测试时可以模拟和填充。

[TestMethod]
public async Task GetCallsProblemOnInvalidId() {
    //Arrange
    var problemDetails = new ProblemDetails() {
        //...populate as needed
    };
    var mock = new Mock<ProblemDetailsFactory>();
    mock
        .Setup(_ => _.CreateProblemDetails(
            It.IsAny<HttpContext>(),
            It.IsAny<int?>(),
            It.IsAny<string>(),
            It.IsAny<string>(),
            It.IsAny<string>(),
            It.IsAny<string>())
        )
        .Returns(problemDetails)
        .Verifyable();

    var sut = new MyController(...);
    sut.ProblemDetailsFactory = mock.Object;

    //...

    //Act
    var result = await sut.Get(someInvalidId);

    //Assert
    mock.Verify();//verify setup(s) invoked as expected

    //...other assertions
}
Run Code Online (Sandbox Code Playgroud)