2017-01-18 241 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答案,因爲他正確地回答了這個問題,並