【发布时间】:2015-08-13 12:10:47
【问题描述】:
我正在尝试为依赖于 HttpContext 并使用 cookie 的组件编写集成测试的方法。
我的问题是当它尝试向响应 cookie 写入任何内容时抛出异常。
这里有一些重现问题的代码。
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web;
using Moq;
namespace CookieTest
{
[TestClass]
public class CookieTest
{
private Mock<HttpContextBase> _httpContextMock;
[TestInitialize]
public void SetUp()
{
var request = new HttpRequest(null, "http://localhost/", "");
var stream = new MemoryStream();
var sw = new StreamWriter(stream);
var response = new HttpResponse(sw);
_httpContextMock = new Mock<HttpContextBase>();
_httpContextMock.Setup(t => t.Request).Returns(new HttpRequestWrapper(request));
_httpContextMock.Setup(t => t.Response).Returns(new HttpResponseWrapper(response));
}
[TestMethod]
public void TestCookieWrite()
{
var httpContext = _httpContextMock.Object;
var expectedValue = "value";
var cookies = httpContext.Response.Cookies;
var cookieToAdd = new HttpCookie("key", expectedValue);
// to illustrate that these are not null
Assert.IsNotNull(cookies);
Assert.IsNotNull(cookieToAdd);
// System.NullReferenceException: Object reference not set to an instance of an object.
// at System.Web.HttpCookieCollection.Add(HttpCookie cookie)
// at CookieTest.CookieTest.TestCookieWrite() in CookieTest.cs: line 41
cookies.Add(cookieToAdd);
Assert.AreEqual(expectedValue, httpContext.Response.Cookies.Get("key"));
}
}
}
【问题讨论】:
-
这是完整的堆栈跟踪吗?似乎很奇怪,因为
Addmethod 看起来不应该自己抛出 NRE... -
嗨@JamesThorpe,是的,这是完整的堆栈跟踪。我有点疑惑。
-
我还查看了 .NET 源代码,但似乎找不到哪里出错了
-
我刚刚复制了它 - 我的堆栈跟踪在顶部有
System.Web.HttpResponse.OnCookieAdd(HttpCookie cookie),在Add方法上方。 -
看起来它正在链接到Request's cookies。
标签: c# .net unit-testing testing