【问题标题】:Unit Tests for Methods that use Generic Types使用泛型类型的方法的单元测试
【发布时间】: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


【解决方案1】:

您正在自定义版本的 ReadOnlyDictionary 中测试 ContainsKey 方法。在这种情况下,我相信要测试的主要点是,一旦将键添加到字典中,当使用该键调用此方法时,该方法将返回 true。

在这种情况下,什么都不重要,具体是实际放入字典中,只要在检查已添加/未添加的键时得到正确的真/假响应即可。

因此,在您的测试中,您可以只删除 TODO,因为您不关心数据是什么。

再深入一点,您的自定义类似乎只是 source 成员的包装器(至少对于此方法而言)。对类进行单元测试的另一种方法可能是注入源代码并使用模拟来确定源代码是否被正确操作,而不是测试实际的字典功能是否正常工作。在不了解您的班级的情况下,目前很难说哪种方法更好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2013-10-28
    • 2021-02-16
    相关资源
    最近更新 更多