gpt4 book ai didi

c# - ASP.NET MVC 单元测试和 HttpContext.Current.Cache 有问题

转载 作者:太空宇宙 更新时间:2023-11-03 22:22:52 25 4
gpt4 key购买 nike

这是我的 Controller 代码的第一部分:

public class ControlMController : Controller
{
IControlMService _controlMservice;

public IList<User> Users
{
get
{
if (System.Web.HttpContext.Current.Cache["users"] == null)
{

System.Web.HttpContext.Current.Cache["users"] = _controlMservice.GetUsers();
}
return (IList<User>)System.Web.HttpContext.Current.Cache["users"];
}
}

public ControlMController(IControlMService controlMservice)
{
this._controlMservice = controlMservice;
var users = Users;
ViewData["Users"] = users;
ViewData["jqSelectUsers"] = string.Join(";", users.Select(x => x.UserID + ":" + x.Name).ToArray());
}

我正在尝试对其进行测试,并且因为我正在使用 HttpContext 进行缓存,所以我正在努力处理空引用异常。我试过 using MvcContrib.TestHelper; 这是我的示例测试...

    [TestMethod]
public void EventDetails_Returns_view_with_correct_event()
{
var builder = new TestControllerBuilder();
var controller = builder.CreateController<ControlMController>(
new ControlMService(
new MockControlMRepository()
));
var view = (controller.EventDetails(1) as ViewResult);
Assert.AreEqual(1, (view.ViewData.Model as Event).EventId);
}

(我还没想好使用 DI 进行测试!)

当代码命中 httpcontext 时,我仍然得到相同的空引用异常:

Error   1   TestCase 'SupportTool.Tests.Services.ControlM.ControlMControllerTests.EventDetails_Returns_view_with_correct_event'
failed: System.NullReferenceException: Object reference not set to an instance of an object.
at SupportTool.web.Controllers.ControlMController.get_Users()

有什么想法吗?

最佳答案

我认为当您的测试运行时 HttpRuntime.Cache 不会为 null。

关于c# - ASP.NET MVC 单元测试和 HttpContext.Current.Cache 有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2496019/

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