你如何测试MVC .net中的cookie?

时间:2021-09-14 07:28:43

http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx

This post shows how to test setting a cookie and then seeing it in ViewData. What I what to do is see if the correct cookies were written (values and name). Any reply, blog post or article will be greatly appreciated.

这篇文章展示了如何测试设置cookie然后在ViewData中查看它。我该怎么做才能看看是否写了正确的cookie(值和名称)。任何回复,博客文章或文章将不胜感激。

3 个解决方案

#1


7  

Are you looking for something more like this? (untested, just typed it up in the reply box)

你在寻找更像这样的东西吗? (未经测试,只需在回复框中输入)

var cookies = new HttpCookieCollection();
controller.ControllerContext = new FakeControllerContext(controller, cookies);
var result = controller.TestCookie() as ViewResult;
Assert.AreEqual("somevaluethatshouldbethere", cookies["somecookieitem"].Value);

As in, did you mean you want to test the writing of a cookie instead of reading one? Please make your request clearer if possible :)

就像在,你的意思是你想要测试cookie的写作而不是读一个?请尽可能让您的要求更清楚:)

#2


1  

Perhaps you need to pass in a Fake Response object that the cookies are written to, and you test what is returned in that from the Controller.

也许您需要传入写入cookie的Fake Response对象,并测试Controller中返回的内容。

#3


-2  

function ReadCookie(cookieName) {
 var theCookie=""+document.cookie;
 var ind=theCookie.indexOf(cookieName);
 if (ind==-1 || cookieName=="") return ""; 
 var ind1=theCookie.indexOf(';',ind);
 if (ind1==-1) ind1=theCookie.length; 
 return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}

#1


7  

Are you looking for something more like this? (untested, just typed it up in the reply box)

你在寻找更像这样的东西吗? (未经测试,只需在回复框中输入)

var cookies = new HttpCookieCollection();
controller.ControllerContext = new FakeControllerContext(controller, cookies);
var result = controller.TestCookie() as ViewResult;
Assert.AreEqual("somevaluethatshouldbethere", cookies["somecookieitem"].Value);

As in, did you mean you want to test the writing of a cookie instead of reading one? Please make your request clearer if possible :)

就像在,你的意思是你想要测试cookie的写作而不是读一个?请尽可能让您的要求更清楚:)

#2


1  

Perhaps you need to pass in a Fake Response object that the cookies are written to, and you test what is returned in that from the Controller.

也许您需要传入写入cookie的Fake Response对象,并测试Controller中返回的内容。

#3


-2  

function ReadCookie(cookieName) {
 var theCookie=""+document.cookie;
 var ind=theCookie.indexOf(cookieName);
 if (ind==-1 || cookieName=="") return ""; 
 var ind1=theCookie.indexOf(';',ind);
 if (ind1==-1) ind1=theCookie.length; 
 return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}