簡體   English   中英

C#Prime因素Kata中的單元測試失敗

[英]Unit test failure in C# Prime Factors Kata

長期的程序員,C#的新手。 剛開始使用VS2012和內置測試框架的Prime Factor Kata。 在第一次測試時,預期和實際匹配,但它被標記為失敗。 任何人都可以解釋為什么,更重要的是解決方法是什么?

using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PrimeFactorsKata
{
    [TestClass]
    public class UnitTest1
    {
        private static List<int> ExpectedList()
        {
            return new List<int>();
        }

        [TestMethod]
        public void TestOne()
        {
            Assert.AreEqual(ExpectedList(), PrimeFactorGenerator.Generate(1));
        }
    }

    class PrimeFactorGenerator
    {
        public static List<int> Generate(int n)
        {
            return new List<int>();
        }
    }
}

輸出:

Assert.AreEqual failed. 
Expected:<System.Collections.Generic.List`1[System.Int32]>. 
Actual:<System.Collections.Generic.List`1[System.Int32]>. 

   at PrimeFactorsTest.UnitTest1.TestOne() in UnitTest1.cs: line 17

您正在嘗試比較兩個不同的對象引用。

Assert.AreEqual(ExpectedList(), PrimeFactorGenerator.Generate(1));

這是調用ExpectedList()然后調用PrimeFactorGenerator.Generate(1) 每個調用都是創建並返回對對象的引用(因為你有new關鍵字)。 Assert.AreEqual()然后比較顯然不相同的引用。

了解引用和對象內容之間的區別非常重要。 引用是指向對象值(內容)的指針。

您需要做的是遍歷兩個列表並比較內容(假設您在其中插入了一些數據,在您的示例中它們是空的但是此代碼仍然有效):

var l1 = ExpectedList();
var l2 = PrimeFactorGenerator.Generate(1);

Assert.AreEqual(l1.Count, l2.Count);

if (l1.Count > 0) //Make sure you have data
    for (int i = 0, i < l1.Count, i++)
        Assert.AreEqual(l1[i], l2[i]);

正如其他人所提到的,你正在比較每個列表的引用,這些引用是不同的。 要比較內容,可以使用CollectionAssert.AreEqual

[TestMethod]
public void TestOne()
{
    CollectionAssert.AreEqual(ExpectedList(), PrimeFactorGenerator.Generate(1));
}

您還可以查看像AreEquivalent這樣的CollectionAssert上的其他方法

每個都有覆蓋,允許您傳遞IComparer以確定如何比較集合中的項目。

C#中引用類型的缺省相等是實例相等 - 您的斷言失敗,因為這兩個參數不是List<T>的相同實例。 有沒有現成的Assert在MSTest的序列平等的,但你可以使用像Enumerable.SequenceEqualAssert.IsTrue達到同樣的效果,如

[TestMethod]
public void TestOne()
{
    Assert.IsTrue(ExpectedList().SequenceEqual(PrimeFactorGenerator.Generate(1));
}

編輯:

顯然MSTest中集合斷言(感謝@juharr),這將簡化您的測試

[TestMethod]
public void TestOne()
{
    CollectionAsssert.AreEquivalent(ExpectedList(), PrimeFactorGenerator.Generate(1));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM