![](/img/trans.png)
[英]Is the order of the two parameters in Assert.AreEqual(expected, actual) important?
[英]Visual Studio Unit Testing Assert.AreEqual Fails with Identical Expected and Actual Values
在單元測試方面,我是個新手,如果這完全是愚昧,請原諒我。 但是,即使我為期望值和實際值提供了完全相同的值,也無法通過此方法通過單元測試。 當我設置斷點並逐步執行時,我已經確認期望變量和實際變量都是一個包含兩個項目的字符串數組,等等。 但是,每次指出“ Assert.AreEqual失敗。期望:System.String []實際:System.String []”時,測試仍然失敗。
namespace TestProject1
{
public class Testing
{
public string[] PMDate(string lastPm)
{
if (string.IsNullOrEmpty(lastPm))
return new []{"blah", "blah"};
string[] results = lastPm.Split(new[] {" "}, StringSplitOptions.None);
if (results.Length < 2)
return new[] {"blah", "blah"};
return results;
}
}
[TestClass()]
public class UnitTest1
{
[TestMethod()]
public void PmDateTest()
{
Testing test = new Testing();
string[] expected = test.PMDate("01/01/1900");
string[] actual = test.PMDate("01/01/1900");
Assert.AreEqual(expected, actual);
}
}
}
您的測試將使用object.Equals
,它不會被數組覆蓋。 換句話說,這將輸出false:
var x = new[] { 0 };
var y = new[] { 0 };
Console.WriteLine(x.Equals(y));
您應該對集合使用CollectionAssert
:
CollectionAssert.AreEqual(expected, actual);
之所以失敗是因為字符串數組是兩個不同的對象,即使它們包含相同的值,它們也是不同的對象。 您可以通過在運行時檢查Expected.GetHashcode()和actual.GetHashCode()來簡單地驗證這一點,您會發現哈希碼是不同的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.