2009-08-11 97 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)); 
}