gpt4 book ai didi

c# - 如何单元测试 Core MVC Controller 操作是否调用 ControllerBase.Problem()

转载 作者:行者123 更新时间:2023-12-03 14:38:21 24 4
gpt4 key购买 nike

我们有一个源自 ControllerBase 的 Controller 用这样的 Action :

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

最佳答案

null 异常是因为缺少 ProblemDetailsFactory
在这种情况下, Controller 需要能够创建 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
}

关于c# - 如何单元测试 Core MVC Controller 操作是否调用 ControllerBase.Problem(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60740134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com