3

我对 ac# 测试方法有疑问。

看起来像:

public void GetRolesTest()
{
    RoleProvider target = new RoleProvider(); 
    string username = "FOO"; 
    string[] expected = new string[2];
    expected[0] = "Admin";
    expected[1] = "User";
    string[] actual;
    actual = target.GetRoles(username);
    Assert.AreEqual<string[]>(expected, actual);
}

被测试的方法只是做以下事情:

public override string[] GetRoles(string username)
{
    string[] output = new string[2];
    output[0] = "Admin";
    output[1] = "User";
    return output;
}

运行测试后,我收到以下错误:

Error in "Assert.AreEqual". Expected:<System.String[]>. Acutally:<System.String[]>.

有人能告诉我那里有什么问题吗?

4

2 回答 2

5

你得到你的例外的原因是Assert.AreEqual它将使用默认的比较器类型,在这种情况下string[]将是简单的引用比较(actual并且expected是不同的对象 - 不同的引用)。

您可以改用集合断言:

CollectionAssert.AreEquivalent(expected, actual);

或者,true使用 LINQ 进行验证:

Assert.IsTrue(actual.SequenceEqual(expected));
于 2012-06-12T07:47:35.200 回答
2

What you're testing here is whether actual and expected are the same array instance, which it is not the case. I would recommend testing the array contents explicitly, like this:

Assert.Contains( "Admin", actual );
Assert.Contains( "User", actual );
Assert.Equals( 2, actual.Length );

Depending on your unit testing lib the code may look slightly different, but I hope you see what I'm getting at.

于 2012-06-12T07:27:22.727 回答