2013-02-25 7 views
10

मैं एमवीसी 4 और टीडीडी के लिए नया हूं।एमवीसी 4 टीडीडी - सिस्टम। ऑर्ग्यूमेंट नल अपवाद: मूल्य शून्य नहीं हो सकता है।

जब मैं इस परीक्षण को चलाने का प्रयास करता हूं तो यह विफल रहता है, और मुझे नहीं पता कि क्यों। मैंने कई चीजों की कोशिश की है जो मैं सर्किलों में घूमना शुरू कर रहा हूं।

// 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); 

    } 

और परिणाम: क्योंकि Request संपत्ति है कि आप अपने ApiController अंदर उपयोग कर रहे हैं आरंभ नहीं किया है

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

उपयोग और विधि दर्ज करते हैं, कुछ' एक तरफ ध्यान दें पर null' – LukeHennerley

+0

होना चाहिए, इकाई परीक्षण से कोई भी स्थिर का उपयोग कभी नहीं करना चाहिए डीबी की तरह संसाधन। आपको इन निर्भरताओं को इंजेक्ट करना चाहिए। क्या होता है जब आपका डीबी बदलता है? आपका यूनिट परीक्षण बेकार है! – Liam

+0

मुझे लगता है कि डीबी शून्य या डीबी है। उपयोगकर्ता शून्य है। –

उत्तर

20

आप परीक्षण में विफल रहा है। सुनिश्चित करें कि आप इसे प्रारंभ यदि आप इसे उपयोग करना चाहते हैं सुनिश्चित करें: अपने डीबगर में `चरण over`

//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

संबंधित मुद्दे