Back to Repositories

Testing Array-Based Hash Map Operations in hello-algo

This test suite validates the functionality of an array-based hash map implementation in Go, covering core operations like insertion, retrieval, deletion, and traversal methods. The tests verify both basic hash map operations and edge cases while ensuring proper key-value pair management.

Test Coverage Overview

The test suite provides comprehensive coverage of array hash map operations:
  • Initialization and creation of hash map structure
  • Key-value pair insertion with put() method
  • Value retrieval using get() method
  • Key-value pair removal functionality
  • Multiple iteration methods including pairSet(), keySet(), and valueSet()

Implementation Analysis

The testing approach utilizes Go’s native testing framework with a focus on behavioral verification:
  • Sequential operation testing with clear state validation
  • Direct method invocation pattern for hash map operations
  • Formatted output verification using fmt package
  • Structured test flow from basic to complex operations

Technical Details

Testing infrastructure includes:
  • Go testing package (testing.T)
  • fmt package for output formatting
  • Custom hash map implementation (newArrayHashMap)
  • String-based verification of operation results
  • Integrated console output for visual verification

Best Practices Demonstrated

The test implementation showcases several testing best practices:
  • Logical grouping of related operations
  • Clear test case separation and documentation
  • Comprehensive operation verification
  • Multiple traversal method validation
  • Proper cleanup and resource management

krahets/hello-algo

zh-hant/codes/go/chapter_hashing/array_hash_map_test.go

            
// File: array_hash_map_test.go
// Created Time: 2022-12-14
// Author: msk397 ([email protected])

package chapter_hashing

import (
	"fmt"
	"testing"
)

func TestArrayHashMap(t *testing.T) {
	/* 初始化雜湊表 */
	hmap := newArrayHashMap()

	/* 新增操作 */
	// 在雜湊表中新增鍵值對 (key, value)
	hmap.put(12836, "小哈")
	hmap.put(15937, "小囉")
	hmap.put(16750, "小算")
	hmap.put(13276, "小法")
	hmap.put(10583, "小鴨")
	fmt.Println("\n新增完成後,雜湊表為\nKey -> Value")
	hmap.print()

	/* 查詢操作 */
	// 向雜湊表中輸入鍵 key ,得到值 value
	name := hmap.get(15937)
	fmt.Println("\n輸入學號 15937 ,查詢到姓名 " + name)

	/* 刪除操作 */
	// 在雜湊表中刪除鍵值對 (key, value)
	hmap.remove(10583)
	fmt.Println("\n刪除 10583 後,雜湊表為\nKey -> Value")
	hmap.print()

	/* 走訪雜湊表 */
	fmt.Println("\n走訪鍵值對 Key->Value")
	for _, kv := range hmap.pairSet() {
		fmt.Println(kv.key, " -> ", kv.val)
	}

	fmt.Println("\n單獨走訪鍵 Key")
	for _, key := range hmap.keySet() {
		fmt.Println(key)
	}

	fmt.Println("\n單獨走訪值 Value")
	for _, val := range hmap.valueSet() {
		fmt.Println(val)
	}
}