我正在編寫單元測試,我遇到的其中一個問題是不屬於DI的私有類或未在構造函數參數上初始化的空例外。任何人都可以幫助我?這是我的代碼。我的問題是,如何模擬PPortalSessionVariables類。在構造函數中未初始化調用私有類方法
控制器:
public class EducatorController : BaseController
{
//Note: PPortalSessionVariables class should NOT be part of IOC
private readonly IPPortalSessionVariables _ppsessionVariable = new PPortalSessionVariables();
private readonly IEducatorService _educatorService;
public EducatorController(IEducatorService educatorService)
{
_educatorService = educatorService;
}
public ActionResult Index()
{
//during test null exception occurs on _ppsessionVariable.CurrentChild.Id
var model = _educatorService.GetEducatorsForChild(Convert.ToInt64(_ppsessionVariable.CurrentChild.Id));
return View(model);
}
}
測試類:
[TestClass]
public class EducatorControllerTests
{
public EducatorController CreateController(Mock<IEducatorService> educatorService = null)
{
educatorService = educatorService ?? new Mock<IEducatorService>();
HttpContext.Current = HttpMockHelpers.FakeHttpContextCurrent();
var controller = new EducatorController(educatorService.Object);
controller.SetFakeControllerContext("?site=2");
return controller;
}
[TestMethod]
public void Index_Get_ReturnIndexView()
{
var ppsessionVariable = new Mock<IPPortalSessionVariables>();
var controller = CreateController();
var child = new ChildModel();
child.Id = 0;
ppsessionVariable.Setup(x => x.CurrentChild).Returns(child);
var result = controller.Index() as ViewResult;
Assert.IsNotNull(result);
}
}
謝謝你解決了我的問題。 –