gpt4 book ai didi

c# - 依赖响应 cookie 的集成测试抛出 System.NullReferenceException

转载 作者:行者123 更新时间:2023-11-28 20:41:11 24 4
gpt4 key购买 nike

我正在尝试找到一种方法来为依赖于 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"));
}
}
}

最佳答案

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

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

关于c# - 依赖响应 cookie 的集成测试抛出 System.NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31987870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com