2011-02-22 5 views
3

현재 TryUpdateModel()을 사용하는 삽입 메소드를 테스트하려고합니다. 나는 필요한 컨트롤러 콘텍스트를 위장하고있다. 비록 작동한다고해도 설치 한 모델을 게시하지 않는 것처럼 보인다. 여기 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(); 

트릭을 수행합니다. 이제 게시됩니다.

관련 문제