2014-04-18 19 views
0

我有一個基於關我CodedUI測試項目的屬性的報告中的一些代碼。我希望能夠給TestCategoryAttribute添加到該報告,但我不知道如何去適應我的代碼,允許像下面重複屬性:如何獲取重複方法的屬性值?

[TestMethod] 
[TestCategory("Smoke")] 
[TestCategory("Feature1")] 
public void CodedUITest() 
{ 
} 

下面的代碼工作的時候我只有一個TestCategory但會不能與多個測試類別按上述方式工作:

//Other code above to find all CodedUI classes and all public, nonstatic methods with the TestMethod attribute 

//find method with testcategory attribute 
if (attrs.Any(x => x is TestCategoryAttribute)) 
{ 
    var testcategoryAttr = (TestCategoryAttribute)attrs.SingleOrDefault(x => x is TestCategoryAttribute); 
    string testCategories = string.Join(", ", testcategoryAttr.TestCategories.Select(v => v.ToString())); 
} 
+2

你不能真的要求'SingleOrDefault'並獲取多個項目......不知道你確切需要什麼,但絕對不是'SingleOrDEfault'。 –

回答

0

這是最終爲我工作的解決方案。我問一個實際的開發者這個問題,而不是試圖找出自己(我QA):)我不得不添加一些特殊的邏輯,因爲attr.TestCategories對象是一個列表正確格式的字符串。

//find method with testcategory attribute 
if (attrs.Any(x => x is TestCategoryAttribute)) 
{ 
    var testCategoryAttrs = attrs.Where(x => x is TestCategoryAttribute); 
    if (testCategoryAttrs.Any()) 
    { 
     foreach (var testCategoryAttr in testCategoryAttrs) 
     { 
      TestCategoryAttribute attr = (TestCategoryAttribute)testCategoryAttr; 
      testCategories += string.IsNullOrEmpty(testCategories) 
       ? string.Join(", ", attr.TestCategories) 
       : string.Format(", {0}", string.Join(", ", attr.TestCategories)); 
     } 
    }        
} 
1

Where更換SingleOrDefault

var testcategoryAttrs = attrs.Where(x => x is TestCategoryAttribute) 
          .Select(x => ((TestCategoryAttribute)x).TestCategory); 
string testCategories = string.Join(", ", testcategoryAttrs.ToArray()); 

我不知道在TestCategoryAttribute屬性名,所以我在此示例中使用的TestCategory

+0

由於ToArray()產生了一個對象類型列表,而不是實際的值,所以你的解決方案並不完美。 – PBMax

+0

這很奇怪。嘗試重新聲明'testcategoryAttrs'爲'IEnumerable的'而不是'var'。並且請確保您將我的示例中的TestCategory屬性替換爲實際屬性名稱,該屬性名稱返回屬性的數據字符串。 – Dmitry

0

SingleOrDefault如果有多個項目與您的條件一致,則會拋出異常。在這種情況下,您有兩個屬性,這就是您獲取異常的原因。

如果你想只有一個項目,然後用FirstOrDefault。它返回與條件符合項目否則返回所以你應該鑄造返回的FirstOrDefault結果時謹慎的第一個項目,你可能要添加劇組之前空檢查,因爲你正在使用Any方法,並確保至少存在一個TestCategoryAttribute存在,在這種情況下不需要空值檢查。

var testcategoryAttr = (TestCategoryAttribute)attrs 
         .FirstOrDefault(x => x is TestCategoryAttribute);