簡體   English   中英

如何在C#/ VS中構建自定義斷言?

[英]How to build custom assertions in C#/VS?

我在一些代碼中遇到了一個錯誤,它從一些文本中提取元數據並將其放入字典中。

當我比較兩個字典對象時,我的測試失敗了,因為鍵的順序不同。 我真的不在乎鍵的順序。

我想有一個斷言方法,如:

Assert.AreEquivalent(propsExpected,propsActual)

這將評估如下:

Assert.AreEqual(propsExpected.Count, propsActual.Count);
foreach (var key in propsExpected.Keys)
{
    Assert.IsNotNull(props[key]);
    Assert.AreEqual(propsExpected[key], props[key]);
}

最好的方法是什么?

如果你能使用LINQ,


void Main()
{
    Dictionary d1 = new Dictionary<int, string>();
    Dictionary d2 = new Dictionary<int, string>();  

    d1.Add(1, "1");
    d1.Add(2, "2");  
    d1.Add(3, "3");  

    d2.Add(2, "2");  
    d2.Add(1, "1");  
    d2.Add(3, "3");  

    Console.WriteLine(d1.Keys.Except(d2.Keys).ToArray().Length);  
}

這將0打印到控制台。 除了試圖在上面的例子中找到兩個列表之間的差異。

您可以將其與0進行比較,以查找是否存在任何差異。

編輯:在執行此操作之前,您可以添加檢查以比較2個詞典的長度。
只有長度不同時才可以使用Except。

使用NUnit,您可以使用Is.EquivalentTo()約束比較兩個集合。 此約束將評估集合並檢查集合是否具有相同的元素,但它不關心順序。

CollectionEquivalentConstraint的文檔如果你不使用NUnit,那么你正在使用的測試框架中是否存在類似的東西?

正如@Sprintstar在@Michael La Voie回答的評論中指出的那樣,Assert類因為它的靜態特性而無法擴展,我解決這個問題的方法通常是創建一個包含我的自定義方法的測試庫在同一方法中發生多個斷言和其他驗證。 對於前

public static class MyTestRepository
{   
    public static void ArePropsEquivalent(
        Dictionary<string, int> propsExpected, 
        Dictionary<string, int> propsActual)
    {
        //Multiple Asserts and validation logic
        //required for Equivalence goes here
    }

    public static void ArePropsSimilar(
        Dictionary<string, int> propsExpected, 
        Dictionary<string, int> propsActual)
    {
        //Multiple Asserts and validation logic 
        //required for similarity goes here
    }
}

然后我從單元測試方法中調用這些方法。

[TestMethod]
public void TestMthod1()
{
    //Props declaration goes here
    MyTestRepository.ArePropsEquivalent(propsExpected, propsActual);
}

[TestMethod]
public void TestMthod2()
{
    //Props declaration goes here
    MyTestRepository.ArePropsSimilar(propsExpected, propsActual);
}

通過這種方式,我可以在實際的單元測試用例方法中編寫更少的內容,並保持模塊化(在不同型號的情況下)。

它現在是可能的(可能是MS自問題最初回答以來添加的) - 如果你使用That單例,擴展將會起作用。

在這種情況下,擴展可以被稱為:

Assert.That.AreEquivalent(propsExpected,propsActual);

這里的訣竅是使用.Net 3.5的新功能,稱為擴展方法

例如,要使用上面提供的代碼獲取Assert類以支持AreEquivalent方法,您可以執行以下操作:

public static class MyAssertExtensions
{
    public static void AreEquivalent(this Assert ast, 
        Dictionary<string, int> propsExpected, 
        Dictionary<string, int> propsActual)
    {
        Assert.AreEqual(propsExpected.Count, propsActual.Count);
        foreach (var key in propsExpected.Keys)
        {
            Assert.IsNotNull(props[key]);
            Assert.AreEqual(propsExpected[key], props[key]);
        }
    }
}

這樣你就可以像這樣調用斷言:

Assert.AreEquivalent(propsExpected,propsActual);

暫無
暫無

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

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