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
使用'步驟over'在調試器和輸入法,一定有東西'null' – LukeHennerley 2013-02-25 15:25:59
在一個側面說明,單元測試不應該訪問沒有靜態像db的資源。你應該注入這些依賴關係。你的數據庫變化時會發生什麼?你的單元測試是無用的! – Liam 2013-02-25 15:26:05
我想那個數據庫是空的或db.Users是空的。使用調試器來檢查 – 2013-02-25 15:26:38