Reputation: 8477
I'm using Microsoft Unit Test for unit testing my .NET Classes. I have method that I uses generic types and when I use the wizard, it creates two methods, one is a helper using a GenericParameterHelper.
I can update the test to a specific type but I'm wondering what the best approach to test generics would be.
Here are the two test methods that the Unit Test Wizard produced:
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>();
}
The method I'm testing (from the custom 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);
}
What value should I use to initialize each of the values that have a TODO?
Upvotes: 1
Views: 1122
Reputation: 447
You are testing the ContainsKey method in your custom version of ReadOnlyDictionary. In this case, I believe the primary point being tested is that once a key is added to the dictionary this method returns true when called with that key.
In this case, it should't matter what, specifically is actually put into the dictionary, as long as you get the proper true / false response when checking for key that has / has not been added.
So, in your test, you can just remove the TODOs as you don't care what the data is.
Going a bit deeper, it appears that your custom class is just a wrapper for whatever the source member is (at least for this method). Another way to unit test your class might be to inject source and use mocks to determine that source is being properly manipulated, rather than testing that the actual dictionary functionality is working. Hard to say which approach is better at this point without knowing more about your class.
Upvotes: 2