Skip to content

Add unit tests for hashtable with classes as keys #123

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 13, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions Tests/HashtableTests/HashtableTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,63 @@ public void Hashtable_InsertNullKey()
}, "No exception was thrown when adding a NULL key.");
}

[TestMethod]
public void Hashtable_InsertClassAsKey()
{
Hashtable ht = new Hashtable();

/////////////
OutputHelper.WriteLine("Adding element with a 'string' as key.");

ht.Add("Key 1", 9999);

/////////////
OutputHelper.WriteLine("Adding element with a 'class' as key.");

ht.Add(new SomeKey(), 8888);

/////////////
OutputHelper.WriteLine("Adding element with another 'class' as key.");

ht.Add(new SomeOtherKey(7777), 7777);
}

[TestMethod]
public void Hashtable_ClassAsKey()
{
var hashtable = new Hashtable();

OutputHelper.WriteLine("Adding 100 elements to the hashtable with SomeKey class");

for (int i = 0; i < 100; i++)
{
SomeKey key = new SomeKey();

hashtable.Add(key, key.GetHashCode());
}

foreach (var key in hashtable.Keys)
{
Assert.AreEqual(key.GetHashCode(), (int)hashtable[key], $"Failed on the {key} key.");
}

hashtable = new Hashtable();

OutputHelper.WriteLine("Adding 100 elements to the hashtable with SomeOtherKey class");

for (int i = 0; i < 100; i++)
{
SomeOtherKey key = new SomeOtherKey(i);

hashtable.Add(key, key.I.GetHashCode());
}

foreach (var key in hashtable.Keys)
{
Assert.AreEqual((key as SomeOtherKey).I.GetHashCode(), (int)hashtable[key], $"Failed on the {key} key.");
}
}

#region helper classes and methods

/// <summary>
Expand Down Expand Up @@ -783,6 +840,28 @@ public static Hashtable CreateStringHashtable(int count, int start = 0)
return hashtable;
}

public class SomeKey
{
}


public class SomeOtherKey
{
private readonly int _i;

public int I => _i;

public SomeOtherKey()
{
}

public SomeOtherKey(int i)
{
_i = i;
}

}

private class Foo
{
public string StringValue { get; set; } = "Hello World";
Expand Down