如何对核心MVC控制器动作是否进行单元测试调用ControllerBase.Problem()

问题描述 投票:0回答:1

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

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

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

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

}

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

c# unit-testing asp.net-core-mvc core controller-action
1个回答
1
投票

空异常是由于缺少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
    };
}

Source

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

Source

在单独测试时可能会被模拟和填充。

[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
}
© www.soinside.com 2019 - 2024. All rights reserved.