【问题标题】:Integration tests with dependencies on response cookies throwing System.NullReferenceException依赖于响应 cookie 的集成测试抛出 System.NullReferenceException
【发布时间】: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"));
        }
    }
}

【问题讨论】:

  • 这是完整的堆栈跟踪吗?似乎很奇怪,因为 Add method 看起来不应该自己抛出 NRE...
  • 嗨@JamesThorpe,是的,这是完整的堆栈跟踪。我有点疑惑。
  • 我还查看了 .NET 源代码,但似乎找不到哪里出错了
  • 我刚刚复制了它 - 我的堆栈跟踪在顶部有 System.Web.HttpResponse.OnCookieAdd(HttpCookie cookie),在 Add 方法上方。
  • 看起来它正在链接到Request's cookies

标签: c# .net unit-testing testing


【解决方案1】:

响应包含一个名为 _context 的私有字段,如果您像这样设置该字段,则该字段需要引用自身和请求:

var response = new HttpResponse(sw);
response.GetType()
        .GetField("_context", BindingFlags.NonPublic | BindingFlags.Instance)
        .SetValue(response, new HttpContext(request, response));
_httpContextMock = new Mock<HttpContextBase>();

然后NullReferenceException 将不再被抛出。此外,当您将 HttpCookie 对象与字符串进行比较时,测试失败,您需要编辑断言以检查 Value 属性,如下所示:

Assert.AreEqual(expectedValue, httpContext.Response.Cookies.Get("key").Value);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    相关资源
    最近更新 更多