2016-08-12 16 views
6

私はnunitを使って単体テストを作成していますが、このコードはすべて実行時に正常に動作します。値にnullを設定することはできません。パラメータ名:request

私はこのコントローラを返すときに私のコントローラから呼び出されているこの保護された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メソッドを呼び出す前に、要求を指定することが必須と考えています。

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

     Configuration = new HttpConfiguration() 
    }; 

は、それが動作するかどうか、私に教えてください:

また、コンフィギュレーション(HttpConfiguration)を必要とするかもしれません。

+0

これは私の仕事: MyControllerコントローラー=新しいMyController(){要求=新しいSystem.Net.Http.HttpRequestMessage() }; –

7

あなたが得ている理由:Requestオブジェクトがnullあるので

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.

です。

enter image description here

そのための解決策は、以下のようなあなたのテストであなたのコントローラのインスタンスを作成することです:私たちは初期化されているMyApiControllerクラスの新しいインスタンスを作成するときに、このように

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

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); 
    } 
} 
関連する問題