![](/img/trans.png)
[英]How to accommodate specflow step definition to accept deferent number of parameters from specflow feature file with one method
[英]Get the path from a SpecFlow feature file in a Step Definition
是否可以在運行時在“步驟定義”中檢索SpecFlow功能文件的路徑?
片段:
[Given(@"Some given statement")]
public void GivenSomeGivenStatement() {
var featureFilePath = // retrieve the path of the feature file
// that executes this step.
}
語境:
我們對數據庫和查詢進行測試。 源數據在Excel文件和.SQL文件中創建(用於檢查查詢)。 這些源數據是大型數據集,無法放入特征文件本身或使用SpecFlow.Plus.Excel擴展名。
為了使數據與要素文件保持一致,我們希望將此數據與要素文件本身放在同一文件夾中。 為此,我們需要該功能文件的路徑,因此我們也有testdata的路徑。
這是一個建議。 這只是我快速整理的內容,因此有很大的改進空間。 它依賴於功能文件名與描述中提供的功能標題相同。 它還假定您具有SpecFlow VS項目的常規文件夾結構,因為存在許多字符串操作。
首先,調用代碼應使用SpecFlow BeforeScenario屬性。 像這樣:
public void BeforeScenario()
{
//grabs Feature Title from SpecFlow context
var featureName = FeatureContext.Current.FeatureInfo.Title;
//Calls method to obtain path of file
var featureFilePath = GetFeatureFilePath(featureName);
}
GetFeatureFilePath方法將如下所示:
private static string GetFeatureFilePath(string featureName)
{
string startupPath = Environment.CurrentDirectory;
var splitStartupPath = startupPath.Split(new[] {"\\"}, StringSplitOptions.None);
var featureFolder = splitStartupPath[0] + @"\\" +
splitStartupPath[1] + @"\\" +
splitStartupPath[2] + @"\\" +
splitStartupPath[3] + @"\\" +
splitStartupPath[4] + @"\\" +
splitStartupPath[5] + @"\\Features\";
var dir = new DirectoryInfo(featureFolder);
foreach (var fi in dir.GetFiles())
{
if (fi.FullName.Contains(featureName))
return fi.FullName;
}
return "No Feature File Found With Title: " + featureName;
}
它會抓取您的當前目錄,並將其拆分到Features文件夾應位於的位置。 然后,它會遍歷每個功能文件,直到找到在其路徑名中包含功能標題的文件,並將其作為完整路徑返回。
我目前不知道有任何其他方式來獲得此功能。
我不認為知道功能部件文件的路徑是可行的,因為功能部件文件用於生成包含單元測試的文件,並將其編譯並復制到測試運行目錄中。
最簡單的事情是將文件設置為解決方案的一部分,然后在項目構建時將它們復制到輸出目錄。
如果您使用NUnit作為測試框架,則文件應該與測試正在執行的目錄位於同一目錄中,因此您應該能夠在不指定任何路徑的情況下加載它們,或者使用Assembly.GetExecutingAssembly()。Location查找位置該代碼實際上正在執行。
如果您使用的是MSTest,則需要向測試添加[DeploymentItem(FileToDeploy)]
屬性,以確保文件在運行時隨測試一起實際部署。 不幸的是,隨着Specflow生成測試,它不會為您添加此功能。 為了解決這個問題,您需要創建一個部分類,該部分類與包含測試的類同名。 此類與名稱最后帶有“ Feature”標記的功能相同。 因此,如果您的功能中有此功能:
Feature: Do A Thing
您的測試類將稱為DoAThingFeature
所以您需要創建一個這樣的局部類:
[DeploymentItem("FileToDeploy.ext")]
public partial class DoAThingFeature
{}
以確保MsTest將所需的文件復制到正確的目錄。
編輯
根據您的評論,您可能會做類似的事情
將標簽添加到功能@hasFiles @source:myFile.xlsx
然后,您可以添加此類:
[Binding]
public class DeployFiles
{
[BeforeScenario("hasFiles")]
public void CopyFiles()
{
..in here find the current executing directory and search
..the subtree for any files defined in the
..ScenarioInfo.Tags array that start with `source:` and copy
..them to the current executing directory
}
}
那么所有帶有@hasFiles
標簽的@hasFiles
都會將@source
標簽指定的所有文件部署到運行測試的根目錄。
不漂亮,我不確定它會起作用,但是可能會。
也許這可能對您有所幫助,在.net 4.5中,您可以保留調用方的路徑,並查看.net 4.5中的此線程源路徑
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.