使用最小起订量对 Web API 控制器 actualResult 进行单元测试未按预期运行

Unit testing a Web API controller actualResult using moq does not behave as expected

单元测试控制器返回 IHttpActionResult 原因

System.NullReferenceException: 'Object reference not set to an instance of an object.

[HttpGet]
public async Task<IHttpActionResult> Get(Guid myId)
{    
    var myaccount = await _myaccountService.GetMyAccount(myId);
    return Ok(myaccount);
}

测试方法中的代码

var actualResult = (await controller.Get(It.IsAny<Guid>()) as OkNegotiatedContentResult<IEnumerable<MyAccount>>).Content;

Returns

System.NullReferenceException: 'Object reference not set to an instance of an object.**

[TestMethod]
public async Task GeMyAccount_Returns_CorrectData()
{
      // Arrange         
      var expectedResult = new List<MyAccount>
     {
         new  MyAccount
          {
           Id = "1",
           Name = "Name1"
          },
         new  MyAccount
          {
           Id = "2",
           Name = "Name2"
          },
     };

    //Act 
    var mockMyAccountService = new Mock<IMyAccountService>();
    mockMyAccountService.Setup(mock => 
    mock.GetMyAccount(It.IsAny<Guid>())).Returns(Task.FromResult(expectedResult));
    var controller = new MyAccountController(mockMyAccountService.Object);

     var actualResult = (await controller.Get(It.IsAny<Guid>()) as 
    OkNegotiatedContentResult<IEnumerable<MyAccount>>).Content;
    mockOnrAccountService.Verify(m => m.GetMyAccount(It.IsAny<Guid>()));
    Assert.AreEqual(expectedResult, actualResult);

不确定我做错了什么。

您在 mockMyAccountService 中的 GetMyAccount 方法应该是 List<MyAccount> 作为 return 类型。由此看来,MyAccountControllerGet 方法也应该是 return 一种 OkNegotiatedContentResult<List<MyAccount>> 而不是 OkNegotiatedContentResult<IEnumerable<MyAccount>> 的类型。所以,问题出在你不正确的类型转换上。