使用moq对Web API控制器actualResult进行单元测试的行为不符合预期



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

系统。NullReferenceException: 'Object reference not set to a instance of 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;

返回

系统。NullReferenceException: 'Object reference not set to a instance of 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);

我不知道我做错了什么。

您的GetMyAccount方法在mockMyAccountService中期望List<MyAccount>作为返回类型。由此,MyAccountControllerGet方法也有望返回OkNegotiatedContentResult<List<MyAccount>>类型而不是OkNegotiatedContentResult<IEnumerable<MyAccount>>。所以,问题出在你不正确的类型转换上。

相关内容

  • 没有找到相关文章

最新更新