我想在我的控制器中测试一个操作,该操作使用 controllerContext 作为参数来生成基于第 3 部分库“Rotativa”的 pdf 文档。
这是动作(功能)的实现:
public ActionResult DetailsPrint(int? id)
{
var a = new ViewAsPdf();
a.ViewName = "../Ops/_2A1/Details";
a.Model =UnitOfWork._2A1s.Get(id.Value);
var pdfBytes = a.BuildPdf(ControllerContext);
// return ActionResult
MemoryStream ms = new MemoryStream(pdfBytes);
return new FileStreamResult(ms, "application/pdf");
}
这就是我试图让单元测试工作的方式:
构造函数
public _2A1ControllerTest() { _mockRepository = new Mock<I2A1Repository>(); var mockUoW = new Mock<IUnitOfWork>(); _mockHttpContext = new Mock<HttpContextBase>(); _mockRequest = new Mock<HttpRequestBase>(); _mockDisplayModeContext = new Mock<IDisplayMode>(); mockUoW.SetupGet(u => u._2A1s).Returns(_mockRepository.Object); _mockHttpContext.SetupGet(x => x.Request).Returns(_mockRequest.Object); _controller = new _2A1Controller(mockUoW.Object); _controller.MockCurrentUser("test.admin"); _controller.ControllerContext = new ControllerContext(_mockHttpContext.Object, new System.Web.Routing.RouteData(), _controller); }
测试功能
[TestMethod] public void DetailsPrint_shouldPrint() { var result = _controller.DetailsPrint(1) as ActionResult; result.Should().BeOfType<ActionResult>(); }
测试名称:DetailsPrint_shouldPrint 测试全名:OPSReviewTest._2A1ControllerTest.DetailsPrint_shouldPrint 测试源:C:\inetpub\wwwroot\OpsReview\OPSReviewTest\Controllers\Api_2A1ControllerTest.cs:第 46 行测试结果:失败测试持续时间:0:04:39,3039007 结果 StackTrace :
在 System.Web.WebPages.DisplayModeProvider.GetDisplayMode(HttpContextBase context) 在 System.Web.Mvc.ControllerContext.get_DisplayMode() 结果消息:测试方法 OPSReviewTest._2A1ControllerTest.DetailsPrint_shouldPrint 抛出异常:System.NullReferenceException:对象引用未设置为对象的实例。
任何帮助或建议,谢谢。