Moq是Asp.Net MVC控制器中的假cookie

时间:2014-03-23 00:20:37

标签: asp.net-mvc moq

这是我对登录控制器的操作。我能够使用Moq模拟动作。 但是当我遇到 this.HttpContext.Response.Cookies.Set(新的HttpCookie(“AcceptedDoDNotice”){Expires = DateTime.Now.AddDays(-1)});

错误:其他信息:未将对象引用设置为对象的实例。

我如何模拟cookie以便我不会得到上面的错误?

public ActionResult Login(LoginViewModel model)
{
        if (ModelState.IsValid)
        {

            var user = _uow.UserRepository.FindLogin(model.Email, model.Password);
            if (user != null)
            {
                _uow.UserRepository.UpdateLastLoginDate(user);                    
                _uow.SaveChanges();

                this.HttpContext.Response.Cookies.Set(new HttpCookie("MyCookie") { Expires = DateTime.Now.AddDays(-1) });

                if (user.UserLevel.IsAdmin)
                    return RedirectToAction("Index", "Administrator");

            }
            else
            {
                ModelState.AddModelError("", "Invalid username or password.");
            }
        }


        return View(model);
}

Moq测试如下:             //安排             var model = new LoginViewModel();             model.Email = realEmail;             model.Password = realPassword;

        //Act
        var loginController = new LoginController();
        var result = loginController.Login(model) as RedirectToRouteResult;
        var actual = result.RouteValues["controller"].ToString();

        //Assert
        actual.Should().Be("Administrator");

1 个答案:

答案 0 :(得分:4)

您需要模拟控制器上下文。这将允许您提供模拟响应,反过来提供您控制的cookie集合。然后,您可以确切地看到响应中设置了哪些cookie。

var cookieCollection = new HttpCookieCollection { };
var response = new Mock<HttpResponseBase>();
response.SetupGet(r => r.Cookies).Returns(cookieCollection);

var context = new Mock<HttpContextBase>();
context.SetupGet(x => x.Response).Returns(response.Object);

var loginController = new LoginController();
loginController.ControllerContext = new ControllerContext(context.Object, new RouteData(), loginController);

var model = new LoginModel { };
var result = loginController.Login(model) as RedirectToRouteResult;
var actual = result.RouteValues["controller"].ToString();

//Assert
actual.Should().Be("Administrator");
cookieCollection.Should().HaveCount(1);

// other assertions about your cookie