2013-04-11 116 views
6

我有以下代碼(sample1.evol - 文件貼在我的單元測試項目):NUnit測試工作目錄

[Test] 
public void LexicalTest1() 
{ 
    var codePath = Path.GetFullPath(@"\EvolutionSamples\sample1.evol"); 
    //..... 
} 

我發現,測試執行的工作目錄是不大會目錄(在我的案例代碼路徑變量分配給d:\EvolutionSamples\sample1.evol)。

那麼,如何更改執行工作目錄(無硬編碼)呢?加載附加到測試用例的任何文件的最佳做法是什麼?

+0

在開始刪除\或放一個。在之前呢? – 2013-04-11 21:29:55

+7

Nunit有一個[TestContext](http://nunit.org/index.php?p=testContext&r=2.6.2),它包含TestDirectory屬性和WorkDirectory屬性 – Gus 2013-04-11 21:34:10

+0

我的問題是,你爲什麼要讀取單元中的文件測試? – 2013-04-11 21:45:13

回答

2

我用它來進行需要訪問數據文件的集成測試。

在測試需要運行的任何機器上創建一個名爲的系統環境變量TestDataDirectory指向測試數據所在的根目錄。

然後有將獲取你的文件路徑的靜態方法..

public static class TestHelper 
{ 
    const string EnvironmentVariable = "TestDataDirectory"; 
    static string testDataDir = Environment.GetEnvironmentVariable(EnvironmentVariable); 

    public static string GetTestFile(string partialPath) 
    { 
     return Path.Combine(testDataDir, partialPath); 
    } 
} 

...

[Test] 
public void LexicalTest1() 
{ 
    var codePath = TestHelper.GetTestFile(@"\EvolutionSamples\sample1.evol"); 
    //..... 
} 
1

我使用這個代碼:

var str = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase); 
    if (str.StartsWith(@"file:\")){ 
     str = str.Substring(6); 
    } 

在入門str變量彙編目錄。

0

我們遇到了使用ReSharper和NCrunch運行測試的問題,但當給出測試的相對文件路徑時,本機VS Test Runner將無法找到文件。我通過創建一個將相關測試文件路徑傳入的函數來解決此問題,並且它會爲您提供絕對文件路徑。

private static string _basePath = Path.GetDirectoryName(typeof(NameOfYourTestClassGoesHere).Assembly.Location); 
private string GetAbsoluteTestFilePath(string relativePath) => Path.Combine(_basePath, relativePath); 

你會再使用功能,像這樣:

var input = File.ReadAllLines(GetAbsoluteTestFilePath(@"TestData/YourTestDataFile.txt"));