【问题标题】:Unit test failing because of sessions单元测试因会话而失败
【发布时间】:2012-06-21 15:58:37
【问题描述】:

我已经为我的 MVC3 应用程序编写了Custom model binder。我决定使用自定义模型绑定器是因为我正在使用 Sessions 并且单元测试因此而失败。

现在我的问题是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;
    }       
}

控制器

[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);
}

【问题讨论】:

    标签: asp.net-mvc-3 c#-4.0 asp.net-mvc-2 razor modelbinders


    【解决方案1】:

    这个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"));
    } 
    

    【讨论】:

      【解决方案2】:

      我建议使用 Moq(或任何其他模拟数据的工具)并将值传递给控制器​​构造函数。 (不确定,但如果不是过度工程化,使用依赖注入可能会有所帮助)

      【讨论】:

        猜你喜欢
        • 2013-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-12
        • 2014-04-09
        • 2014-06-14
        • 1970-01-01
        相关资源
        最近更新 更多