2016-08-12 104 views
6

我使用nunit創建了一個單元測試,並且所有這些代碼在運行時都能正常工作。值不能爲空。參數名稱:請求

我有這個受保護HttpResponseMessage代碼下面的代碼是由我的控制器在它返回時調用。

然而,一個錯誤:

"Value cannot be null. Parameter name: request" is displaying.

當我檢查請求,它實際上是null

問題: 如何編碼我的單元測試返回HttpResponseMessage

錯誤顯示在這一行:

protected HttpResponseMessage Created<T>(T result) => Request.CreateResponse(HttpStatusCode.Created, Envelope.Ok(result)); 

這裏是我的控制器:

[Route("employees")] 
    [HttpPost] 
    public HttpResponseMessage CreateEmployee([FromBody] CreateEmployeeModel model) 
    { 
     //**Some code here**// 

     return Created(new EmployeeModel 
     { 
      EmployeeId = employee.Id, 
      CustomerId = employee.CustomerId, 
      UserId = employee.UserId, 
      FirstName = employee.User.FirstName, 
      LastName = employee.User.LastName, 
      Email = employee.User.Email, 

      MobileNumber = employee.MobileNumber, 
      IsPrimaryContact = employee.IsPrimaryContact, 
      OnlineRoleId = RoleManager.GetOnlineRole(employee.CustomerId, employee.UserId).Id, 
      HasMultipleCompanies = EmployeeManager.HasMultipleCompanies(employee.UserId) 
     }); 
    } 

回答

1

我認爲發生的事情是,你是不是實例或指定您的請求屬性(HttpRequestMessage)當您新的你的控制器。我相信在通過單元測試調用API方法之前指定請求是強制性的。

您可能還需要配置(HttpConfiguration):

sut = new YourController() 
    { 
     Request = new HttpRequestMessage { 
      RequestUri = new Uri("http://www.unittests.com") }, 

     Configuration = new HttpConfiguration() 
    }; 

讓我知道是否可行。

+0

這爲我工作: 控制器myController的新= myController的(){請求=新System.Net.Http.HttpRequestMessage() }; –

7

爲什麼你所得到的理由是:

An exception of type 'System.ArgumentNullException' occurred in System.Web.Http.dll but was not handled in user code Additional information: Value cannot be null.

是因爲Request對象null

enter image description here

造成這種情況的解決方案是在您的測試,如創建控制器的一個實例:

var myApiController = new MyApiController 
    { 
     Request = new System.Net.Http.HttpRequestMessage(), 
     Configuration = new HttpConfiguration() 
    }; 

通過這種方式,創建MyApiController類的新實例,當我們初始化Request對象。此外,還需要提供關聯的配置對象。

最後,對於你的API控制器單元測試的一個例子是:

[TestClass] 
public class MyApiControllerTests 
{ 
    [TestMethod] 
    public void CreateEmployee_Returns_HttpStatusCode_Created() 
    { 
     // Arrange 
     var controller = new MyApiController 
     { 
      Request = new System.Net.Http.HttpRequestMessage(), 
      Configuration = new HttpConfiguration() 
     }; 

     var employee = new CreateEmployeeModel 
     { 
      Id = 1 
     }; 

     // Act 
     var response = controller.CreateEmployee(employee); 

     // Assert 
     Assert.AreEqual(response.StatusCode, HttpStatusCode.Created); 
    } 
} 
相關問題