如何编写用于更新 IDictionary 的单元测试

How to write a unit test for Updating an IDictionary

我正在尝试为添加或更新 IDictionary<string, string>

的方法编写单元测试

这是我的添加或更新方法:

public static class ExtensionMethods
{ 
    public static void AddOrUpdate(IDictionary<string, string> Dictionary, string 
                                                                     Key, string Value)
    {
        if(Dictionary.Contains(Key)
        {
            Dictionary[Key] = Value;
        }
        else
        {
            Dictionary.Add(Key, Value);
        }
    }
}

这是我的单元测试:

[TestMethod]
public void Checking_Dictionary_Is_Able_To_Update()
{
    // Arrange
    IDictionary inputDictionary = new Dictionary<string, string>();

    inputDictionary.Add("key1", "someValueForKey1");
    inputDictionary.Add("key2", "someValueForKey2");
    string inputKeyValue = "key1";
    string dataToUpdate = "updatedValueForKey1";


    // Act
    // The following method call produces a conversion error
    ExtensionMethods.AddOrUpdate(inputDictionary, inputKeyValue, dataToUpdate);
}

我在调用 AddOrUpdate() 时遇到的错误是我无法将 System.Collections.IDictionary 转换为 System.Collections.Generic.IDictionary 字符串,字符串

任何人都可以指出我可能做错了什么。

Arrange 正在将测试主题设置为错误的类型 IDictionary,而被测方法需要 IDictionary<string, string>

// Arrange
IDictionary<string, string> inputDictionary = new Dictionary<string, string>();
//...code removed for brevity.

或者您甚至可以使用 var

// Arrange
var inputDictionary = new Dictionary<string, string>();
//...code removed for brevity.

接下来被测方法调用了错误的方法来检查集合中是否包含键。

public static void AddOrUpdate(this IDictionary<string, string> Dictionary, string Key, string Value) {
    if (Dictionary.ContainsKey(Key)) { //<-- NOTE ContainsKey
        Dictionary[Key] = Value;
    } else {
        Dictionary.Add(Key, Value);
    }
}

可以改进扩展方法,使其更通用...

public static class ExtensionMethods {
    public static void AddOrUpdate<TKey, TValue>(this IDictionary<TKey, TValue> Dictionary, TKey Key, TValue Value) {
        if (Dictionary.ContainsKey(Key)) {
            Dictionary[Key] = Value;
        } else {
            Dictionary.Add(Key, Value);
        }
    }
}

这允许它与任何 IDictionary<TKey,TValue> 派生类型一起使用并调用..

[TestMethod]
public void _Checking_Dictionary_Is_Able_To_Update() {
    // Arrange
    var inputDictionary = new Dictionary<string, string>();

    inputDictionary.Add("key1", "someValueForKey1");
    inputDictionary.Add("key2", "someValueForKey2");
    string inputKeyValue = "key1";
    string dataToUpdate = "updatedValueForKey1";


    // Act
    inputDictionary.AddOrUpdate(inputKeyValue, dataToUpdate);

    // Assert
    //...
}