我創建了以下控制器:
[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。
我怎樣才能得到這份作業?
uj5u.com熱心網友回復:
Chetan 在評論中提供了答案:
我認為您需要轉換
NotFoundResult為NotFoundObjectResult
你沒有傳遞一個物件,return NotFound()所以你應該使用它NotFoundResult。運算子回傳 null這As就是您收到例外的原因。將斷言更新為:
Assert.Equal(StatusCodes.Status404NotFound, (result as NotFoundResult).StatusCode);
這已經過測驗,并且正在使用您的原始設定為我作業:
_mediator.Setup(x => x.Send(It.IsAny<GetMForProvQuery>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(() => null);
在您澄清您正在使用可選引數之前的原始答案
您確定要為 設定正確的多載_mediator.Send嗎?看起來您正在為Sendin 設定不同的多載:
_mediator.Setup(x => x.Send(It.IsAny<GetMForProvQuery>(), It.IsAny<CancellationToken>()))...
這需要2個引數。但是,您在控制器中使用單個引數呼叫它:
var result = await _mediator.Send(new GetMForProvQuery() { ProvId = provId })
您能否嘗試設定單個引數多載并傳遞一個回傳 null 的操作:
_mediator.Setup(x => x.Send(It.IsAny<GetMForProvQuery>()))
.ReturnsAsync(() => null);
uj5u.com熱心網友回復:
嘗試修復行:
.ReturnsAsync(new CatDto());
到
.ReturnsAsync((CatDto)null);
因為您回傳CatDto物件并且轉換的結果(結果為 NotFoundObjectResult)為 null
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/416269.html
標籤:
上一篇:單元測驗中的類與實體屬性
