【发布时间】:2014-08-11 20:18:05
【问题描述】:
我正在使用 Microsoft Unit Test 对我的 .NET 类进行单元测试。我有使用泛型类型的方法,当我使用向导时,它会创建两种方法,一种是使用 GenericParameterHelper 的助手。
我可以将测试更新为特定类型,但我想知道测试泛型的最佳方法是什么。
以下是单元测试向导生成的两种测试方法:
public void ContainsKeyTestHelper<TKey, TValue>()
{
IDictionary<TKey, TValue> dictionaryToWrap = null; // TODO: Initialize to an appropriate value
ReadOnlyDictionary<TKey, TValue> target = new ReadOnlyDictionary<TKey, TValue>(dictionaryToWrap); // TODO: Initialize to an appropriate value
TKey key = default(TKey); // TODO: Initialize to an appropriate value
bool expected = false; // TODO: Initialize to an appropriate value
bool actual;
actual = target.ContainsKey(key);
Assert.AreEqual(expected, actual);
}
[TestMethod()]
public void ContainsKeyTest()
{
ContainsKeyTestHelper<GenericParameterHelper, GenericParameterHelper>();
}
我正在测试的方法(来自自定义 ReadOnlyDictionary (https://cuttingedge.it/blogs/steven/pivot/entry.php?id=29)):
/// <summary>Determines whether the <see cref="T:ReadOnlyDictionary`2" />
/// contains the specified key.</summary>
/// <returns>
/// True if the <see cref="T:ReadOnlyDictionary`2" /> contains
/// an element with the specified key; otherwise, false.
/// </returns>
/// <param name="key">The key to locate in the
/// <see cref="T:ReadOnlyDictionary`2"></see>.</param>
/// <exception cref="T:System.ArgumentNullException">
/// Thrown when the key is null.
/// </exception>
public bool ContainsKey(TKey key)
{
return this.source.ContainsKey(key);
}
我应该使用什么值来初始化每个具有 TODO 的值?
【问题讨论】:
-
您认为这种方法有什么问题?
-
我不明白这种方法,所以我不确定如何初始化每个值。
-
很难准确地说出您在这里测试的是什么 - 看起来您正在测试 ReadOnlyDictionary 类的 ContainsKey 方法,这不是您编写的类(除非您正在编写您自己的 System.Collections.ObjectModel.ReadOnlyDictionary 版本)。查看您尝试进行单元测试的方法会有所帮助。
-
@ScottMiller,这是来自cuttingedge.it/blogs/steven/pivot/entry.php?id=29 的自定义 ReadOnlyDictionary 的单元测试的一部分(我使用的是没有内置 ReadOnlyDictionary 的 4.0 版)。我已经用 ContainsKey 方法的来源更新了问题。
标签: c# unit-testing generics