简体   繁体   English

如何使用 moq 模拟 ControllerContext? mocking ControllerContext 时出错

[英]How to mock the ControllerContext using moq? ERROR while mocking the ControllerContext

I am using the MOQ Framework and I have the following Unit test and it is failing with the below error message “Object reference not set to an instance of an object” At the below line of code我正在使用 MOQ 框架,并且我有以下单元测试,但它失败并出现以下错误消息“对象引用未设置为对象的实例”在下面的代码行

viewCxt.View.Render(viewCxt, writer);  

Could anyone point me in the right direction please as to why this is not passing the test?谁能指出我正确的方向,为什么这没有通过测试?

[Test]
public void can_call_PopulateBankTransactionWorkQueueViewInTransactionMetaDataAjaxResponseObject()
{

    var transactionMetaData = new TransactionMetaDataDTO() { TransactionId = "1", FileId = "1", LockboxNumber = "0402020", DepositDate = "04.26.2011", BatchId = "1" };


    var request = new Mock<HttpRequestBase>();
    request.Setup(r => r.HttpMethod).Returns("GET");
    var mockHttpContext = new Mock<HttpContextBase>();
    mockHttpContext.Setup(c => c.Request).Returns(request.Object);

    var controllerContext = new ControllerContext(mockHttpContext.Object, new Mock<RouteData>().Object, new Mock<ControllerBase>().Object); 

    var checkWorkQueueController = new CheckWorkQueueController(
          activeDirectorySecurityManager.Object,  businessObjectAdapter, httpRequestObjectHelper.Object, invoiceRepos.Object,  new HtmlHelpers());

    checkWorkQueueController.ControllerContext = controllerContext;
    Assert.DoesNotThrow(() => checkWorkQueueController.PopulateBatchTreeSelectorViewInTransactionMetaDataAjaxResponseObject(transactionMetaData));
}

internal void PopulateBatchTreeSelectorViewInTransactionMetaDataAjaxResponseObject(TransactionMetaDataDTO transactionMetaDataDTO)
{

    var checkWorkQueueViewModel = new CheckWorkQueueViewModel(securityManager, businessObjectAdapter);
    SetActiveFileAndLockbox(transactionMetaDataDTO, checkWorkQueueViewModel, transactionMetaDataDTO.FileId, transactionMetaDataDTO.LockboxNumber);
    transactionMetaDataDTO.BatchTreeSelectorView = htmlHelpers.RenderViewToString(ApplicationConstants.CheckWorkQueueViewPath + ApplicationConstants.BatchTreeSelectorViewFileName, this, checkWorkQueueViewModel);
}

public string RenderViewToString<T>(string viewPath, ControllerBase controller, T model)
{
        controller.ViewData.Model = model;
        using (var writer = new StringWriter())
        {
            var view = new WebFormView(viewPath);
            var vdd = new ViewDataDictionary<T>(model);
            var viewCxt = new ViewContext(controller.ControllerContext, view, vdd, new TempDataDictionary(), writer);
            viewCxt.View.Render(viewCxt, writer);  //ERROR throwing here
            return writer.ToString();
        }
}

Here is the StackTrace:这是堆栈跟踪:

at System.Web.VirtualPath.GetCacheKey()
at System.Web.Compilation.BuildManager.GetCacheKeyFromVirtualPath(VirtualPath virtualPath, Boolean& keyFromVPP)
at System.Web.Compilation.BuildManager.GetVPathBuildResultFromCacheInternal(VirtualPath virtualPath, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean throwIfNotFound)
at System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp)
at System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp)
at System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(String virtualPath, Type requiredBaseType)
at System.Web.Mvc.BuildManagerWrapper.System.Web.Mvc.IBuildManager.CreateInstanceFromVirtualPath(String virtualPath, Type requiredBaseType)
at System.Web.Mvc.WebFormView.Render(ViewContext viewContext, TextWriter writer)

a good way to debug what actually needs to be setup on the Mock is to create it with the MockBehavior.Strict option.调试 Mock 上实际需要设置的内容的一个好方法是使用 MockBehavior.Strict 选项创建它。 So,所以,

var mockHttpContext = new Mock<HttpContextBase>();

becomes变成

var mockHttpContext = new Mock<HttpContextBase>(MockBehavior.Strict);

Then, your test will fail with a MockException when it requires something from the Context that you haven't set up.然后,当您的测试需要您尚未设置的 Context 中的某些内容时,您的测试将失败并出现 MockException。 You can revert to the Loose option later.您可以稍后恢复为“松散”选项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Moq框架中模拟HttpContext(ControllerContext)并进行会话 - How to mock HttpContext (ControllerContext) in Moq framework, and have session 如何模拟ControllerContext.IsChildAction属性? - How to mock ControllerContext.IsChildAction property? 模拟ControllerContext找不到参考 - Mocking ControllerContext could not find reference 如何在没有ControllerContext的情况下从IIdentity模拟GetUserId和IsAuthenticated - How to Mock GetUserId and IsAuthenticated from IIdentity without ControllerContext 模拟ControllerContext.IsChildAction在ParentActionViewContext中引发异常 - Mocking ControllerContext.IsChildAction throws exception in ParentActionViewContext 如何使用 Hangfire 在 BackgroundJob 中使用 Rotativa 获取 ControllerContext 以构建 PDF - How to get ControllerContext to build PDF using Rotativa in BackgroundJob with Hangfire 尝试创建 Mock.Of 时出错<controllercontext> () 用于 ASP.Net Core 3.1 单元测试</controllercontext> - Error trying to create Mock.Of<ControllerContext>() for ASP.Net Core 3.1 Unit Test 如何正确模拟我的controllercontext来测试ViewResult.ExecuteResult()? - How can I correctly mock my controllercontext to test ViewResult.ExecuteResult()? 我应该模拟ControllerContext来对我的JsonNetResult数据进行单元测试 - Should I mock the ControllerContext to unit test my JsonNetResult data 当 mocking 使用 Moq 时,模拟返回 null - Mock returns null when mocking using Moq
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM