以下是控制器代码的第一部分:
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()
有什么想法吗?