3 回答

TA貢獻1797條經驗 獲得超6個贊
在運行時,由于隱式轉換,您的原始測試代碼仍然可以工作。
但是根據提供的調試器圖像,測試似乎對結果的錯誤屬性進行了斷言。
因此,雖然更改被測方法允許測試通過,但無論哪種方式都可以實時運行
ActioResult<TValue> 有兩個屬性,根據使用它的操作返回的內容進行設置。
/// <summary>
/// Gets the <see cref="ActionResult"/>.
/// </summary>
public ActionResult Result { get; }
/// <summary>
/// Gets the value.
/// </summary>
public TValue Value { get; }
來源
因此,當使用Ok()它返回的控制器操作將ActionResult<int>.Result通過隱式轉換設置操作結果的屬性。
public static implicit operator ActionResult<TValue>(ActionResult result)
{
return new ActionResult<TValue>(result);
}
但是測試正在斷言Value屬性(參考 OP 中的圖像),在這種情況下沒有設置。
無需修改被測代碼以滿足測試,它可以訪問該Result屬性并對該值進行斷言
[Fact]
public async Task GetLocationsCountAsync_WhenCalled_ReturnsLocationsCount() {
//Arrange
_locationsService
.Setup(_ => _.GetLocationsCountAsync(It.IsAny<string>()))
.ReturnsAsync(10);
var controller = new LocationsController(_locationsService.Object, null) {
ControllerContext = { HttpContext = SetupHttpContext().Object }
};
//Act
var actionResult = await controller.GetLocationsCountAsync();
//Assert
var result = actionResult.Result as OkObjectResult;
result.Should().NotBeNull();
result.Value.Should().Be(10);
VerifyAll();
}

TA貢獻1806條經驗 獲得超5個贊
問題是將其包裝在Ok. 如果返回對象本身,Value則填充正確。
如果您查看文檔中的Microsoft 示例,他們只會將控制器方法用于非默認響應,例如NotFound:
[HttpGet("{id}")]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<Product> GetById(int id)
{
if (!_repository.TryGetProduct(id, out var product))
{
return NotFound();
}
return product;
}
- 3 回答
- 0 關注
- 196 瀏覽
添加回答
舉報