单元测试控制器返回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>
作为返回类型。由此,MyAccountController
的Get
方法也有望返回OkNegotiatedContentResult<List<MyAccount>>
类型而不是OkNegotiatedContentResult<IEnumerable<MyAccount>>
。所以,问题出在你不正确的类型转换上。