2012-06-21 5 views
2

MVC3 응용 프로그램에 Custom model binder을 기록했습니다. 맞춤 모델 바인더를 사용하기를 원했는데 그 이유는 세션과 단위 테스트를 사용하고 있기 때문입니다.세션으로 인해 단위 테스트에 실패했습니다

이제 내 문제는 About 작업이 매개 변수를 허용하지 않지만 세션을 사용하지 않고 보려면 장바구니에 저장된 값을 전달해야한다는 것입니다. 세션이 있기 때문에 단위 테스트가 실패합니다. 모델 바인더는 매개 변수로 카트를 About에 전달한 경우에만 작동합니다.

아이디어가 있으면 알려주세요.

많은 감사

모델 바인더

public class CartModelBinder : IModelBinder 
{ 
    private const string CartSessionKey = "Cart"; 

    public object BindModel(ControllerContext controllerContext, ModelBindingContext modelBindingContext) 
    { 
     Cart cart = null; 

     if(IsCartExistInSession(controllerContext)) 
     { 
      cart = GetCartFromSession(controllerContext); 
     } 
     else 
     { 
      cart = new Cart(); 
      AddCartToSession(controllerContext, cart); 
     } 
     return cart; 
    } 

    private static Cart GetCartFromSession(ControllerContext controllerContext) 
    { 
     return controllerContext.HttpContext.Session[CartSessionKey] as Cart; 
    } 

    private static void AddCartToSession(ControllerContext controllerContext, Cart cart) 
    { 
     controllerContext.HttpContext.Session[CartSessionKey] = cart; 
    } 

    private static bool IsCartExistInSession(ControllerContext controllerContext) 
    { 
     return controllerContext.HttpContext.Session[CartSessionKey] != null; 
    }  
} 

내가 사용 MOQ (또는 데이터를 조롱하기위한 다른 도구)를 제안하고 값을 전달할 것

[HttpPost] 
public ActionResult AddToCartfromAbout(Cart cart, int productId = 2) 
{ 
    var product = _productRepository.Products.First(p => p.ProductId == productId); 
    cart.AddItem(product, 1); 
    return View("About"); 
} 

public ActionResult About() 
{ 
    // Need something here to get the value of cart 
    return View(cart); 
} 

답변

2

Link이 문제를 해결할 수 있습니다. 위의 링크에서 소스와 DLL을 다운로드해야하며 테스트에서 Session에 값을 할당 할 수 있습니다.

[Test] 
public void AddSessionStarShouldSaveFormToSession() 
{ 
    // Arrange 
    TestControllerBuilder builder = new TestControllerBuilder(); 
    StarsController controller = new StarsController(); 
    builder.InitializeController(controller); 
    controller.HttpContext.Session["NewStarName"] = "alpha c"; 

    // Act 
    RedirectResult result = controller.Index() as RedirectResult; 

    // Assert 
    Assert.IsTrue(result.Url.Equals("Index")); 
} 
0

컨트롤러 컨트롤러 생성자에서. (확실하지는 않지만 mabe는 의존성 주입을 사용하면 너무 많은 엔지니어링이 아니라면 도움이됩니다)

관련 문제