1

我正在使用 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 的值?

4

1 回答 1

2

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

在这种情况下,只要在检查已添加 / 未添加的键时获得正确的真 / 假响应,具体是实际放入字典中的内容并不重要。

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

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

于 2012-10-26T20:14:34.363 回答