FindView 返回的模拟视图
我想模拟(使用最小起订量)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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用 It.IsAny <布尔>而不是在设置 FindView 方法时只是 false。
You should use It.IsAny < bool > instead of just false when setup FindView method.