2010-07-30 105 views
3

我最近做了一些我的mvc应用程序的重构,并意识到有很多静态视图返回。我决定创建一个控制器,它返回静态视图(如果它们存在的话),并在视图不存在时抛出404错误,而不是使用具有仅返回视图的动作结果的多个控制器。单元测试ViewEngines.Engines.FindView的正确方法是什么?

public ActionResult Index(string name) 
{ 
    ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, name, null); 

    if (result.View == null) 
     ThrowNotFound("Page does not exists."); 

    return View(name); 
} 

我的问题是什么是单元测试的正确方法呢?我尝试了下面的代码,但是我得到的错误是“RouteData必须包含一个名为'controller'的项目,其中包含一个非空字符串值”。

[Theory] 
[InlineData("ContactUs")] 
public void Index_should_return_view_if_view_exists(string name) 
{ 
    controller = new ContentController(); 
    httpContext = controller.MockHttpContext("/", "~/Content/Index", "GET"); ; 

    var result = (ViewResult)controller.Index(name); 

    Assert.NotNull(result.View); 
} 

我的意图是让单元测试外出并获取真实的视图。然后我开始想知道是否应该用ViewGate的SetupGet模拟ViewEngines并创建两个测试,其中第二个测试如果视图为空则测试未找到的异常。

什么是测试此功能的正确方法?任何指针,示例代码或博客文章都会有所帮助。

感谢

回答

4

您应该创建一个嘲笑视图引擎,并把它收集在:

[Theory] 
[InlineData("ContactUs")] 
public void Index_should_return_view_if_view_exists(string name) 
{ 
    var mockViewEngine = MockRepository.GenerateStub<IViewEngine>(); 
    // Depending on what result you expect you could set the searched locations 
    // and the view if you want it to be found 
    var result = new ViewEngineResult(new [] { "location1", "location2" }); 
    // Stub the FindView method 
    mockViewEngine 
     .Stub(x => x.FindView(null, null, null, false)) 
     .IgnoreArguments() 
     .Return(result); 
    // Use the mocked view engine instead of WebForms 
    ViewEngines.Engines.Clear(); 
    ViewEngines.Engines.Add(mockViewEngine); 

    controller = new ContentController(); 

    var actual = (ViewResult)controller.Index(name); 

    Assert.NotNull(actual.View); 
} 
+0

达林,谢谢!你能澄清“locations1”,“locations2”吗?假设我的视图位于〜Views/Content/ContactUs.aspx,我希望上面的测试能够找到它。我如何设置ViewEngineResult? – Thomas 2010-08-01 08:31:49

+0

无论你的观点在哪里。在单元测试项目中没有看法。这是嘲笑视图引擎的关键。 'location1'和'location2'只是为了让编译器感到高兴。根本不用。你可以在那里放一个空字符串集合。但在现实世界中,它们代表了您的视图引擎尝试搜索视图的位置。 – 2010-08-01 08:34:48

+0

因此,在您的示例result.View为空,所以当测试运行视图将不会被发现。我将如何去测试反向?我想测试是否发现视图。 – Thomas 2010-08-01 08:48:56

相关问题