亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 ActionResult<T> 進行單元測試?

如何使用 ActionResult<T> 進行單元測試?

C#
神不在的星期二 2021-10-24 17:16:10
我有一個 xUnit 測試,如:[Fact]public async void GetLocationsCountAsync_WhenCalled_ReturnsLocationsCount(){    _locationsService.Setup(s => s.GetLocationsCountAsync("123")).ReturnsAsync(10);    var controller = new LocationsController(_locationsService.Object, null)    {        ControllerContext = { HttpContext = SetupHttpContext().Object }    };    var actionResult = await controller.GetLocationsCountAsync();    actionResult.Value.Should().Be(10);    VerifyAll();}來源是/// <summary>/// Get the current number of locations for a user./// </summary>/// <returns>A <see cref="int"></see>.</returns>/// <response code="200">The current number of locations.</response>[HttpGet][Route("count")]public async Task<ActionResult<int>> GetLocationsCountAsync(){    return Ok(await _locations.GetLocationsCountAsync(User.APropertyOfTheUser()));}結果的值為空,導致我的測試失敗,但如果您查看ActionResult.Result.Value(內部屬性),它包含預期的解析值。請參閱以下調試器的屏幕截圖。如何在單元測試中填充 actionResult.Value?
查看完整描述

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();

}


查看完整回答
反對 回復 2021-10-24
?
忽然笑

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;

}


查看完整回答
反對 回復 2021-10-24
  • 3 回答
  • 0 關注
  • 196 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號