Try   HackMD

[快速筆記] MSTest 夾帶檔案

tags: Test MSTest C#

前言

剛好在進行測試的時候遇到需要夾帶測試檔的情況,其最下方參考來源所提供的方法有很多種,但這邊只紀錄需求上用到的部分,有興趣可以去點延伸閱讀一下。

目錄

說明

這邊主要會使用到DeploymentItemAttribute其用處就是指定每個測試需部屬的檔案或目錄,用法我們就接著看下去吧。

實作

程式碼

這邊說明一下DeploymentItem

  • 第一個參數:要部屬的檔案其相對或絕對路徑。
  • 第二個參數:將檔案複製到指定的路徑下。

因此可以很清楚知道想要在測試流程內取得檔案只需要透過我們所指定的參數即可,程式代碼如下:

[TestMethod] [DeploymentItem(@"TestFile.txt", "TestStaticFile")] public void UploadTest() { var filePath = @"TestStaticFile\TestFile.txt"; var MyFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); // ... }

其專案的資料結構如下

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

設定

除了指定好部屬行為以外還需要進行一些設定,需將檔案設定成有更新時才複製(或永遠複製),這樣才可以將檔案一起發行目錄下,之後執行測試才會將檔案移至指定的路徑,設定圖如下:

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

如果想直接改代碼的話如下

<!-- <your project>.csproj --> <ItemGroup> <None Update="TestFile.txt"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup>

結果查閱

測試專案主要建置或運行主要會是在<your project>\bin\Debug\...底下,我們可以直接在資料夾內部看到我們所設定的測試檔順利的被部屬過去了,在這種情況下程式碼內部就才可以順利讀取到測試檔案。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
需要測試或是偵錯測試才會進行部屬,單純建置是不會複製檔案的唷!!



相關參考來源:
How to: Deploy Files for Tests