Skip to content
May 30, 2013 / windperson

Visual Studio Test專案使用csv或excel file做測試資料的方法

  1. 在測試專案內加入有測試資料的.csv或.xslx檔案,Copy to Output Directory選Copy if newer或Copy always均可。
  2. 要使用測試資料的測試類別內需加上一個TextContext類型的屬性叫TextContext
    public TestContext TestContext { get; set; }
    
  3. 測試Method的Attribute得這樣寫(假設測試資料檔名為MyInputData):

    • CSV檔:

      [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "MyInputData", "MyInputData#csv",DataAccessMethod.Sequential),DeploymentItem("MyInputData.csv"),TestMethod]
      
    • Excel的xlsx檔(假設資料是在該測試檔的MySheet分頁上):

      [DataSource("System.Data.Odbc", @"Dsn=Excel Files;Driver={Microsoft Excel Driver (*.xlsx)};Dbq=|DataDirectory|\\MyInputData.xlsx;defaultdir=.;readonly=true", "MySheet$", DataAccessMethod.Sequential), DeploymentItem("MyInputData.xlsx"), TestMethod]
      
  4. 若使用Excel檔須注意的是測試環境所安裝的Office版本,若系統上安裝的是64位元版的Office,測試專案的Default Processor Architecture需設為x64:
    Set Test Project Processor Architecture

其他細節請參考官方說明:
http://msdn.microsoft.com/EN-US/library/ms182527.aspx

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: