2011-02-22 85 views
3

我當前正試圖測試使用TryUpdateModel()的插入方法。我僞裝需要的controllercontext,雖然這工作似乎並沒有發佈我設置的模型。使用MStest和moq測試TryUpdateModel()

這裏是我的測試方法:

[AcceptVerbs(HttpVerbs.Post)] 
    [GridAction] 
    public ActionResult _SaveAjaxEditing(int? id) 
    { 
     if (id == null) 
     { 
      Product product = new Product(); 
      if (TryUpdateModel(product)) 
      { 
       //The model is valid - insert the product. 
       productsRepository.Insert(product);// AddToProducts(product); 
      } 
     } 
     else 
     { 
      var recordToUpdate = productsRepository.Products.First(m => m.ProductID == id); 
      TryUpdateModel(recordToUpdate); 
     } 
     productsRepository.Save(); 
     return View(new GridModel(productsRepository.Products.ToList())); 
    } 

這裏是我目前的測試:

 [TestMethod] 
    public void HomeControllerInsert_ValidProduct_CallsInsertForProducts() 
    { 
     //Arrange 
     InitaliseRepository(); 

     var httpContext = CustomMockHelpers.FakeHttpContext(); 
     var context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller); 
     controller.ControllerContext = context; 
     //controller.ControllerContext = new ControllerContext(); 

     var request = Mock.Get(controller.Request); 
     request.Setup(r => r.Form).Returns(delegate() 
               { 
                var prod = new NameValueCollection 
                    { 
                     {"ProductID", "9999"}, 
                     {"Name", "Product Test"}, 
                     {"Price", "1234"}, 
                     {"SubCatID", "2"} 
                    }; 
                return prod; 
               }); 


     // Act: ... when the user tries to delete that product 
     controller._SaveAjaxEditing(null); 
     //Assert 
     _mockProductsRepository.Verify(x => x.Insert(It.IsAny<Product>())); 
    } 

的方法被調用,但是當它到達TryUpdateModel()現在看來,這不能拾取發佈的對象。任何指向我出錯的地方都會很棒。

回答

6

對其進行排序。似乎完全嘲笑Httpcontext是矯枉過正。

controller.ControllerContext = new ControllerContext(); 

var prod = new FormCollection 
      { 
       {"ProductID", "1"}, 
       {"Name", "Product Test"}, 
       {"Price", "1234"}, 
       {"SubCatID", "2"} 
      }; 

controller.ValueProvider = prod.ToValueProvider(); 

這是訣竅。現已發佈。