asp.net-mvc-3 - 由于 session 而导致单元测试失败

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

我写了Custom model binder对于我的 MVC3 应用程序。我决定使用自定义模型绑定(bind)器是因为我正在使用 session 并且单元测试因此而失败。

现在我的问题是 About 操作不接受任何参数,但它需要传递存储在购物车中的值以在不使用 session 的情况下进行查看。因为使用 session 会使单元测试失败。仅当我将购物车作为参数传递给 About 时,模型绑定(bind)器才起作用。

如果您有任何想法,请建议我。

非常感谢

模型绑定(bind)器

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

Controller

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

最佳答案

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

关于asp.net-mvc-3 - 由于 session 而导致单元测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11142084/

相关文章:

c# - MVC asp.net 序列化如何在 Controller 操作上为 Json 对象工作?

javascript - 在 MVC 2 编辑器模板中正确注册 JavaScript 和 CSS

c# - 在数据库 mvc2 c# 4.0 中存储时以字节为单位减少图像

c# - 在不发送重定向的情况下使用 Controller 和 Action?

asp.net-mvc - ASP.NET MVC 缺少什么?

asp.net-mvc-3 - 异步 Controller 输出缓存

excel - C#-Excel 互操作性

.net - 数据库层设计问题

c# - 通过编程 Linq/Lambda 创建订单

c# - ASP MVC : Custom Validation Attribute