我正在尝试为添加或更新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字符串,字符串
任何人都可以指出我可能做错了什么。
答案 0 :(得分:1)
安排正在将测试主题设置为错误的类型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);
}
}
可以改进Extension方法,使其更通用......
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
//...
}