我正在尝试在 ASP.NET MVC 3 中对我的控制器上的编辑操作进行单元测试。
我已经通过 nuget 安装了 Mvcontrib.MVC3.TestHelper 来模拟我的控制器上下文,但我仍然收到 NullReferenceException
我的代码如下所示:
[TestMethod]
public void it_should_redirect_to_index_after_editing_a_something_successfully()
{
var something= new SomeThing
{
ID = Guid.NewGuid(),
CreatedAt = DateTime.Now,
LastModified = DateTime.Now,
Owner = "Me",
Status = "new",
Title = "my Title",
Attachments = new List<Attachment>()
};
var repo = new FakeRepository();
var controller = new SomethingsController(repo);
new TestControllerBuilder().InitializeController(controller);
var result = controller.Edit(something) as RedirectToRouteResult;
result.AssertActionRedirect().ToAction<SomethingsController>(x => x.Index());
}
生产代码看起来像这样......
[HttpPost]
public ActionResult Edit(SomeThing something)
{
if (ModelState.IsValid)
{
var _something = _repository.GetDocumentByID(something.ID);
TryUpdateModel(_something);
_something.LastModified = DateTime.Now;
_repository.SaveChanges();
return RedirectToAction("Index","Somethings");
}
return View(something);
}
即使我使用 UpdateModel 或 TryUpdateModel 它总是会因 NullReferenceException 而崩溃......
任何帮助,指针都会很棒......