1

这是我的控制器代码的第一部分:

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

有任何想法吗?

4

1 回答 1

4

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

于 2010-03-22T21:58:00.887 回答