2017-01-18 244 views
1

我有以下的(简化)控制器:单元测试测试OK结果

public async Task<IHttpActionResult> Profile(UpdateProfileModelAllowNulls modelNullable) 
{   
    ServiceResult<ProfileModelDto> result = await _profileService.UpdateProfile(1); 

    return Ok(result);   
} 

和:

public async Task<ServiceResult<ProfileModelDto>> UpdateProfile(ApplicationUserDto user, UpdateProfileModel profile) 
{ 
    //Do something... 
} 

及以下NUnit测试:

[Test] 
     public async Task Post_Profile() 
     { 
      var result = _controller.Profile(new UpdateProfileModelAllowNulls() { Email = "[email protected]", DisplayName = "TestDisplay"}) as OkNegotiatedContentResult<Task<<ProfileModelDto>>; 
      Assert.IsNotNull(result);    
     } 

在我的NUnit测试,我正在尝试使用本教程https://www.asp.net/web-api/overview/testing-and-debugging/unit-testing-with-aspnet-web-api检查确定的结果。

我的问题是,我不能转换为OkNegotiatedContentResult,我假设因为我没有传入正确的对象,但我看不到我应该传入什么对象。据我所知,我传入正确的对象例如:OkNegotiatedContentResult<Task<<ProfileModelDto>>;

但这不起作用。

我也曾尝试:

var result = _controller.Profile(new UpdateProfileModelAllowNulls() { Email = "[email protected]", DisplayName = "TestDisplay"}) as OkNegotiatedContentResult<Task<IHttpActionResult>>; 

但是,这也不行。

谁能帮助?

+0

您是否收到任何错误在我面前也? –

+0

as OkNegotiatedContentResult ? –

回答

2

您控制器是异步,所以你应该把它想:

var result = (_controller.Profile(new UpdateProfileModelAllowNulls() { Email = "[email protected]", DisplayName = "TestDisplay"}).GetAwaiter().GetResult()) as OkNegotiatedContentResult<ProfileModelDto>; 
1

如前所述由@esiprogrammer,方法是异步的,所以我需要添加awaiter。

我能够做修复它下面:

var result = _controller.Profile(new UpdateProfileModelAllowNulls() { Email = "[email protected]", DisplayName = "TestDisplay"}); 
    var okResult = await result as OkNegotiatedContentResult<ServiceResult<ProfileModelDto>>; 

我已经接受@esiprogrammer答案,因为他正确地回答了这个问题,并