2009-08-11 52 views
0

我有一個簡單的方法,返回字母表中的字母數組。單元測試集合

public char[] GetLettersOfTheAlphabet() { 
    char[] result = new char[26]; 
    int index = 0; 

    for (int i = 65; i < 91; i++) { 
     result[index] = Convert.ToChar(i); 
     index += 1; 
    } 

    return result; 
} 

我試圖單元測試代碼

[TestMethod()] 
public void GetLettersOfTheAlphabetTest_Pass() { 
    HomePage.Rules.BrokerAccess.TridionCategories target = new HomePage.Rules.BrokerAccess.TridionCategories(); 
    char[] expected = new char[] { char.Parse("A"), 
            char.Parse("B"), 
            char.Parse("C"), 
            char.Parse("D"), 
            char.Parse("E"), 
            char.Parse("F"), 
            char.Parse("G"), 
            char.Parse("H"), 
            char.Parse("I"), 
            char.Parse("J"), 
            char.Parse("k"), 
            char.Parse("L"), 
            char.Parse("M"), 
            char.Parse("N"), 
            char.Parse("O"), 
            char.Parse("P"), 
            char.Parse("Q"), 
            char.Parse("R"), 
            char.Parse("S"), 
            char.Parse("T"), 
            char.Parse("U"), 
            char.Parse("V"), 
            char.Parse("W"), 
            char.Parse("X"), 
            char.Parse("Y"), 
            char.Parse("Z")}; 
    char[] actual; 
    actual = target.GetLettersOfTheAlphabet(); 
    Assert.AreEqual(expected, actual); 
} 

它似乎歸結該陣列使用的比較功能。你如何處理這種情況?

+5

您應該使用'A',一個C#字符,而不是char.Parse(「A」)。 – dahlbyk 2009-08-11 17:10:09

回答

4

CollectionAssert.AreEquivalent(預計實際)工作。

我不完全確定它是如何工作的,但它確實符合我的需求。我認爲它會檢查實際列中預期收集存檔中每個項目中的每個項目,並檢查它們是否相同,但順序無關緊要。

+0

來自AreEquivalent的文檔:「如果兩個集合具有相同數量的相同元素,但是它們的順序相同,則兩個集合是等同的。如果元素的值相等,則元素相等,如果它們引用同一個對象,則不相等。 – 2009-08-11 21:17:03

2

只需遍歷數組並比較每個項目。每個陣列中的索引4應該相同。

另一種方法是檢查結果數組是否包含'A','G','K'或隨機字母。

東西我從單元測試得知,有時你必須要麼複製代碼或做更多的工作,因爲這是測試的性質。基本上,單元測試可能不適用於生產站點。

0

您的K在預期數組中是小寫,但我相信代碼會生成大寫字符。如果比較區分大小寫,當兩個數組不匹配時會導致失敗。

0

你也可以做規模試驗和陣列....

Assert.AreEqual(expected.Length,actual.Length)

Assert.AreEqual中值幾抽查(預期[0],實際[0]) ....

0

首先:


Assert.AreEqual(expected.Length,actual.Length); 

然後:


for(int i = 0; i < actual.Length; i++) 
{ 

//Since you are testing whether the alphabet is correct, then is ok that the characters 
//have different case. 
    Assert.AreEqual(true,actual[i].toString().Equals(expected[i].toString(),StringComparison.OrdinalIgnoreCase)); 
} 
4

如果您使用.NET 3.5,您還可以使用SequenceEqual()

[TestMethod()] 
public void GetLettersOfTheAlphabetTest_Pass() { 
    var target = new HomePage.Rules.BrokerAccess.TridionCategories(); 
    var expected = new[] { 'A','B','C', ... }; 

    var actual = target.GetLettersOfTheAlphabet(); 
    Assert.IsTrue(expected.SequenceEqual(actual)); 
}