From 046f26e0e3fecfbd6e89866d060410e0f9fc11a1 Mon Sep 17 00:00:00 2001 From: Gerson Jr <57489438+gmottajr@users.noreply.github.com> Date: Wed, 4 Dec 2024 18:52:04 -0300 Subject: [PATCH] Improve coverage for hash table (#500) --- .../Hashing/HashTableTests.cs | 94 +++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/DataStructures.Tests/Hashing/HashTableTests.cs b/DataStructures.Tests/Hashing/HashTableTests.cs index 10ee6d7d..ce1e0476 100644 --- a/DataStructures.Tests/Hashing/HashTableTests.cs +++ b/DataStructures.Tests/Hashing/HashTableTests.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using DataStructures.Hashing; +using FluentAssertions; using NUnit.Framework; namespace DataStructures.Tests.Hashing; @@ -389,6 +390,99 @@ public void Test_NegativeHashKey_ReturnsCorrectValue() hashTable.Add(new NegativeHashKey(1), 1); Assert.That(hashTable[new NegativeHashKey(1)], Is.EqualTo(1)); } + + [Test] + public void Add_ShouldTriggerResize_WhenThresholdExceeded() + { + // Arrange + var initialCapacity = 4; + var hashTable = new HashTable(initialCapacity); + + // Act + for (int i = 1; i <= 4; i++) // Start keys from 1 to avoid default(TKey) = 0 issue + { + hashTable.Add(i, $"Value{i}"); + } + + // Assert + hashTable.Capacity.Should().BeGreaterThan(initialCapacity); // Ensure resizing occurred + hashTable.Count.Should().Be(4); // Verify count reflects number of added items + } + + + [Test] + public void Add_ThrowsException_WhenKeyIsDefault() + { + // Arrange + var hashTable = new HashTable(); + + // Act & Assert + Action act = () => hashTable.Add(default, "Value"); + act.Should().Throw().WithMessage("*key*"); + } + + [Test] + public void Add_ThrowsException_WhenValueIsDefault() + { + // Arrange + var hashTable = new HashTable(); + + // Act & Assert + Action act = () => hashTable.Add(1, default); + act.Should().Throw().WithMessage("*value*"); + } + + [Test] + public void Add_StoresValueCorrectly() + { + // Arrange + var hashTable = new HashTable(); + + // Act + hashTable.Add(1, "Value1"); + + // Assert + hashTable[1].Should().Be("Value1"); + } + + [Test] + public void Get_ReturnsCorrectValue_ForExistingKey() + { + // Arrange + var hashTable = new HashTable(); + hashTable.Add("key", 42); + + // Act + var value = hashTable["key"]; + + // Assert + value.Should().Be(42); + } + + [Test] + public void Get_ThrowsException_WhenKeyDoesNotExist() + { + // Arrange + var hashTable = new HashTable(); + + // Act & Assert + Action act = () => _ = hashTable["nonexistent"]; + act.Should().Throw(); + } + + [Test] + public void Capacity_Increases_WhenResizeOccurs() + { + var initialCapacity = 4; + var hashTable = new HashTable(initialCapacity); + + for (int i = 1; i <= 5; i++) + { + hashTable.Add(i, $"Value{i}"); + } + + hashTable.Capacity.Should().BeGreaterThan(initialCapacity); + } } public class NegativeHashKey