FindView 返回的模拟视图

发布于 2024-10-21 04:04:53 字数 1208 浏览 1 评论 0原文

我想模拟(使用最小起订量)Findview 方法返回的视图,如下所示,以便该视图不为空:

if ((ViewEngines.Engines.FindView(ControllerContext, viewName, masterName)).View == null)
            {
                viewName = SomeViewName;
            }

我在网上模拟了这样的视图引擎:

var mockViewEngine = new Mock<IViewEngine>();
        // Depending on what result you expect you could set the searched locations
        // and the view if you want it to be found
        Mock<IView> view = new Mock<IView>();
        var result = new ViewEngineResult(new[] { "location1", "location2" });

        // Stub the FindView method
        mockViewEngine
            .Setup(x => x.FindView(It.IsAny<ControllerContext>(), It.IsAny<string>(), It.IsAny<string>(), false))
            .Returns(result);

        // Use the mocked view engine instead of WebForms
        ViewEngines.Engines.Clear();
        ViewEngines.Engines.Add(mockViewEngine.Object);

但是当我运行测试时,它给了我这个错误:

System.NullReferenceException : Object reference not set to an instance of an object.
at System.Web.Mvc.ViewEngineCollection.Find(Func`2 cacheLocator, Func`2 locator)

I want to mock (using MOQ) view returned by Findview method as shown below, so that view is not null:

if ((ViewEngines.Engines.FindView(ControllerContext, viewName, masterName)).View == null)
            {
                viewName = SomeViewName;
            }

i have mocked viewengine like this following an e.g. online:

var mockViewEngine = new Mock<IViewEngine>();
        // Depending on what result you expect you could set the searched locations
        // and the view if you want it to be found
        Mock<IView> view = new Mock<IView>();
        var result = new ViewEngineResult(new[] { "location1", "location2" });

        // Stub the FindView method
        mockViewEngine
            .Setup(x => x.FindView(It.IsAny<ControllerContext>(), It.IsAny<string>(), It.IsAny<string>(), false))
            .Returns(result);

        // Use the mocked view engine instead of WebForms
        ViewEngines.Engines.Clear();
        ViewEngines.Engines.Add(mockViewEngine.Object);

but when i run test it gives me this error:

System.NullReferenceException : Object reference not set to an instance of an object.
at System.Web.Mvc.ViewEngineCollection.Find(Func`2 cacheLocator, Func`2 locator)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

醉南桥 2024-10-28 04:04:53

您应该使用 It.IsAny <布尔>而不是在设置 FindView 方法时只是 false。

You should use It.IsAny < bool > instead of just false when setup FindView method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文