ASP.NET MVC 之 View 測試


項目又出問題了!手賤了一下,使用某個工具整理了一下 View 中的內容,不經意之間,將 View 的輸出中大小寫不小心搞錯了,導致輸出的內容沒有辦法正常解析。

這種問題太隱蔽了,下次再遇到怎么辦呢?

測試我們的 View ,保證下次不再出現這種問題。

比如說,我們有一個控制器 HomeController.cs 來說,其中包含一個名為 About 的 Action ,它使用 About.cshtml 來呈現最終的輸出內容。

About 這個 Action 的定義如下,其中使用了 ViewBag 來傳遞兩個參數到 View 中。

public ActionResult About()
{
    ViewBag.Message = "Your application description page.";

    return View();
}

About.cshtml 的定義如下:

@{
    ViewBag.Title = "About";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>

<p>Use this area to provide additional information.</p>

 

由於 HTML 內容不容易測試,測試的基本思路是將視圖 cshtml 轉化為一個代碼類,這樣我們就可以通過直接執行代碼來獲取它的輸出進行測試了。

 

1. 使用 RazorGenerator 來將 cshtml 轉換為代碼類

 RazorGenerator 項目現在 GitHub 上 ,原來這個項目在 codeplex 上,在 visualstudiogallery  也有一個分身,現在已經遷移到了 GitHub 上。

在 Visual Studio 中,打開 Tools 的 Extensions and Updates... 菜單。

在彈出的對話框中,輸入 Razor Generator 查找這個 Visual Studio 插件,注意要在 online 中查找,在已經安裝的插件中可是找不到的。

點擊 Download 可以下載並安裝。

安裝之后,會提示需要重新啟動 Visual Studio.

2. 設置工具

在項目中,找到你希望將 cshtml 轉化為代碼的 View ,比如我們的 About.cshtml 這個視圖,選中之后。在屬性窗中,設置它的 Custom Tool 為 RazorGenerator,如下所示。

設置之后,你就會看到在 About.cshtml 文件的下面出現了一個新的文件 About.generated.cs 文件,這就是使用這個工具自動生成的代碼文件。

這個文件的輸出內容如下:

#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.34014
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace ASP
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.Web;
    using System.Web.Helpers;
    using System.Web.Mvc;
    using System.Web.Mvc.Ajax;
    using System.Web.Mvc.Html;
    using System.Web.Routing;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.WebPages;
    
    [System.CodeDom.Compiler.GeneratedCodeAttribute("RazorGenerator", "2.0.0.0")]
    [System.Web.WebPages.PageVirtualPathAttribute("~/Views/Home/About.cshtml")]
    public partial class _Views_Home_About_cshtml : System.Web.Mvc.WebViewPage<dynamic>
    {
        public _Views_Home_About_cshtml()
        {
        }
        public override void Execute()
        {
            
            #line 1 "..\..\Views\Home\About.cshtml"
  
    ViewBag.Title = "About";

            
            #line default
            #line hidden
WriteLiteral("\r\n<h2>");

            
            #line 4 "..\..\Views\Home\About.cshtml"
Write(ViewBag.Title);

            
            #line default
            #line hidden
WriteLiteral(".</h2>\r\n<h3>");

            
            #line 5 "..\..\Views\Home\About.cshtml"
Write(ViewBag.Message);

            
            #line default
            #line hidden
WriteLiteral("</h3>\r\n\r\n<p>Use this area to provide additional information.</p>\r\n");

        }
    }
}
#pragma warning restore 1591

按照項目的說明,默認生成的命名空間應該是項目的命名空間。可以在 Custom Tool Namespace 中指定命名空間。

如果希望所有的視圖都生成代碼文件,可以在 Nuget 的 Package Manager 控制台窗口中,執行下面的命令來完成。

Enable-RazorGenerator

生成的文件可以在運行時替換掉原來的 cshtml 文件。

3. 測試

在測試項目中,使用 Nuget 添加對 RazorGenerator.Testing 的引用。

安裝過程中

安裝完成之后。

在我們的測試項目中,添加一個測試,如下所示。

using Microsoft.VisualStudio.TestTools.UnitTesting;
using RazorGenerator.Testing;

namespace UnitTestProject2
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestAboutView()
        {
            var view = new ASP._Views_Home_About_cshtml();
            view.ViewBag.Title = "Hello";
            view.ViewBag.Message = "Hello, RazorGenerator";

            var output = view.Render();
            var expected = @"
<h2>About.</h2>
<h3>Hello, RazorGenerator</h3>

<p>Use this area to provide additional information.</p>
";
            Assert.AreEqual(expected, output);
        }
    }
}

編譯之后,會看到一個錯誤提示,程序集的版本不對。說我們的 MVC 項目使用了 4.0.0.1 版本的 System.Web.Mvc,而現在這個項目中的是 3.0.0.1 版本,當然要換成新的了。

Assembly 'ASPNETMVC_Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' uses 'System.Web.Mvc, Version=4.0.0.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35' which has a higher version than referenced assembly 'System.Web.Mvc, Version=3.0.0.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

這個很容易,刪除原來引用的程序集,添加 4.0.0.1 程序集

重新編譯,又報下面的錯誤。

Assembly 'System.Web.Mvc, Version=4.0.0.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35' uses 'System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' which has a higher version than referenced assembly 'System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

與上面一樣,重新添加 2.0.0.0 版本的 System.Web.Web.Pages 就可以了。

重新編譯,終於通過了,運行一下,天哪,沒有通過,檢查錯誤原因。

Test method UnitTestProject2.UnitTest1.TestAboutView threw exception: 
System.IO.FileNotFoundException: 未能加載文件或程序集“System.Web.Mvc, Version=3.0.0.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35”或它的某一個依賴項。系統找不到指定的文件。警告: 程序集綁定日志記錄被關閉。
要啟用程序集綁定失敗日志記錄,請將注冊表值 [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD)設置為 1。
注意: 會有一些與程序集綁定失敗日志記錄關聯的性能損失。

根本就沒有執行呀,未能加載文件或稱程序集 System.Web.Mvc,Version=3.0.0.1,我們都 4.0.0.1 了,哪里來的 3.0.0.1 呢?添加一個 app.config 文件,加入下面的內容,告訴它直接找我們對應的版本。

兩個程序集都指定一下。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-5.2.2.0" newVersion="4.0.0.1"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="2.0.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

或者網站項目和測試項目都使用 Nuget 來添加 System.Web.Mvc 的引用,來保證一致性。

現在重新運行一下,終於成功了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM