【发布时间】:2022-01-19 23:53:55
【问题描述】:
我创建了以下控制器:
[HttpGet(“{provId}/m”)]
public async Task<IActionResult> GetMForProv (int provId)
{
var result = await _mediator.Send(new GetMForProvQuery() { ProvId = provId });
if (result == null)
{
return NotFound();
}
return Ok(result);
}
还有下面的单元测试:
public class GetMForProvTest
{
private readonly ProvController _sut;
private readonly Mock<IMediator> _mediator;
private readonly Mock<IConfiguration> _configuration;
public GetMForProvTest()
{
_mediator = new Mock<IMediator>();
_configuration = new Mock<Iconfiguration>();
_mediator.Setup(x => x.Send(It.IsAny<GetMForProvQuery>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new CatDto());
_sut = new ProvController(_mediator.Object, _configuration.Object);
}
[Fact]
public async Task ShouldReturnNotFoundResult_AfterGetMForProv()
{
var result = await _sut.GetMForProv(123); // this providerId does not exist
Assert.Equal(StatusCodes.Status404NotFound, (result as NotFoundObjectResult).StatusCode);
}
当我运行上述测试时,在Assert.Equal(…) 行上我得到
对象引用未设置为对象的实例。
(... 因为 NotFoundObjectResult 返回 null。
我怎样才能得到这项工作?
【问题讨论】:
-
你有更完整的堆栈跟踪,以便我们可以看到抛出异常的位置吗?
-
ReturnsAsync(new CatDto());设置为返回一个对象。所以if (result == null)将是 false 并且 Ok 将被返回。 OkResult 无法转换为 NotFoundResult 这就是您收到错误的原因。更改为ReturnsAsync(null);以解决问题。 -
@Chetan
ReturnsAsync(null)不工作。 VS 表示“以下方法和属性之间的调用不明确:'ReturnsExtensions.ReturnsAsync(IReturns >, TResult)”和 'ReturnsExtensions.ReturnsAsync (IReturns >, Func )'” -
我认为您需要强制转换为 NotFoundResult 而不是 NotFoundObjectResult。 docs.microsoft.com/en-us/dotnet/api/…
-
我已经尝试并得到相同的 Intellisense 错误“调用不明确......”我也尝试过
ReturnsAsync((CatDto)null)、ReturnsAsync(default(CatDto))和ReturnsAsync(() => null),但我得到了“未设置对象引用...... ”
标签: c# unit-testing asp.net-core .net-core asp.net-core-webapi