2013-02-25 71 views
10

我是mvc4和TDD的新手。MVC4 TDD - System.ArgumentNullException:值不能爲空。

當我嘗試運行此測試失敗時,我不知道爲什麼。我已經嘗試了很多我開始在圈子裏跑來跑去的東西。

// GET api/User/5 
    [HttpGet] 
    public HttpResponseMessage GetUserById (int id) 
    { 
     var user = db.Users.Find(id); 
     if (user == null) 
     { 
      //return Request.CreateResponse(HttpStatusCode.NotFound); 
      throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound)); 
     } 
     return Request.CreateResponse(HttpStatusCode.OK, user); 

    } 


    [TestMethod] 
    public void GetUserById() 
    { 
     //Arrange 
     UserController ctrl = new UserController(); 
     //Act 

     var result = ctrl.GetUserById(1337); 

     //Assert 
     Assert.IsNotNull(result); 
     Assert.AreEqual(HttpStatusCode.NotFound,result.StatusCode); 

    } 

而且結果:

Test method Project.Tests.Controllers.UserControllerTest.GetUserById threw exception: 
System.ArgumentNullException: Value cannot be null. Parameter name: request 
+0

使用'步驟over'在調試器和輸入法,一定有東西'null' – LukeHennerley 2013-02-25 15:25:59

+0

在一個側面說明,單元測試不應該訪問沒有靜態像db的資源。你應該注入這些依賴關係。你的數據庫變化時會發生什麼?你的單元測試是無用的! – Liam 2013-02-25 15:26:05

+0

我想那個數據庫是空的或db.Users是空的。使用調試器來檢查 – 2013-02-25 15:26:38

回答

20

您測試失敗,因爲Request屬性,您使用的是ApiController內未初始化。確保你初始化它,如果你打算使用它:

//Arrange 
var config = new HttpConfiguration(); 
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/user/1337"); 
var route = config.Routes.MapHttpRoute("Default", "api/{controller}/{id}"); 
var controller = new UserController 
{ 
    Request = request, 
}; 
controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config; 

//Act 
var result = controller.GetUserById(1337); 
+1

像魅力一樣工作,謝謝! – ArniReynir 2013-02-25 15:41:16

相關問題