gpt4 book ai didi

unit-testing - 模拟 HttpContext.Current.ApplicationInstance.Response

转载 作者:行者123 更新时间:2023-12-02 04:50:33 26 4
gpt4 key购买 nike

我正在使用 Nunit 单元测试框架和 Moq 在我的 MVC web 应用程序中模拟对象我有“HttpContext.Current.ApplicationInstance.Response”在我的操作中,当测试包含此代码的操作时,它返回错误,我已经模拟了 httpcontext 但我不知道模拟 applicationInstance.Response 请帮助我伙计们

 public static Mock<HttpContextBase> HttpMock { get; set; }

public void HttpContextMocking(string requesturl)
{HttpMock = new Mock<HttpContextBase>();
var fakeIdentity = new GenericIdentity("sampe@email.com");
var principal = new GenericPrincipal(fakeIdentity, null);
HttpMock.Setup(x => x.User).Returns(principal);
HttpContext.Current = new HttpContext(new HttpRequest("", requesturl, ""), new HttpResponse(null));
HttpContext.Current.User = principal;

//Mocking the Httpcontext User Identity
HttpMock.SetupGet(c => c.User.Identity.Name).Returns("sampe@email.com");}

我在 Nunit 应用程序中收到错误作为对象空引用执行,在我源代码中的代码在调试抛出单元测试时抛出异常

“在此上下文中没有响应。”HttpContext.Current.ApplicationInstance.Response = 'HttpContext.Current.ApplicationInstance.Response' 引发了 'System.Web.HttpException' 类型的异常

最佳答案

尝试模拟响应:

var response1 = new Mock<HttpResponseBase>();
response1.Setup(p => p.Write(A<string>.Ignored)).Callback((string s) => sb.Append(s));

关于unit-testing - 模拟 HttpContext.Current.ApplicationInstance.Response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29142102/

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