Back to Repositories

Testing Adjacency Matrix Graph Operations in hello-algo

This test suite validates the implementation of an adjacency matrix graph data structure in Go, covering essential graph operations and modifications. It demonstrates comprehensive testing of vertex and edge manipulations in an undirected graph structure.

Test Coverage Overview

The test suite provides thorough coverage of fundamental graph operations using an adjacency matrix representation.

Key functionality tested includes:
  • Graph initialization with vertices and edges
  • Edge addition and removal operations
  • Vertex addition and removal capabilities
  • Graph state verification after modifications

Implementation Analysis

The testing approach employs Go’s native testing framework to validate graph operations systematically. The test structure follows a sequential modification pattern, verifying each graph operation’s impact on the overall structure through print statements for visual verification.

Technical patterns include:
  • Direct manipulation of graph structure
  • Index-based vertex referencing
  • State verification through output validation

Technical Details

Testing tools and configuration:
  • Go testing package (testing)
  • fmt package for output verification
  • Custom graph implementation (newGraphAdjMat)
  • Vertex and edge array initialization
  • Matrix-based graph representation

Best Practices Demonstrated

The test implementation showcases several testing quality practices for graph data structures.

Notable practices include:
  • Systematic operation sequencing
  • Clear state verification steps
  • Comprehensive operation coverage
  • Explicit index-based vertex management
  • Clear test case organization

krahets/hello-algo

zh-hant/codes/go/chapter_graph/graph_adjacency_matrix_test.go

            
// File: graph_adjacency_matrix_test.go
// Created Time: 2023-01-31
// Author: Reanon ([email protected])

package chapter_graph

import (
	"fmt"
	"testing"
)

func TestGraphAdjMat(t *testing.T) {
	/* 初始化無向圖 */
	// 請注意,edges 元素代表頂點索引,即對應 vertices 元素索引
	vertices := []int{1, 3, 2, 5, 4}
	edges := [][]int{{0, 1}, {1, 2}, {2, 3}, {0, 3}, {2, 4}, {3, 4}}
	graph := newGraphAdjMat(vertices, edges)
	fmt.Println("初始化後,圖為:")
	graph.print()

	/* 新增邊 */
	// 頂點 1, 2 的索引分別為 0, 2
	graph.addEdge(0, 2)
	fmt.Println("新增邊 1-2 後,圖為")
	graph.print()

	/* 刪除邊 */
	// 頂點 1, 3 的索引分別為 0, 1
	graph.removeEdge(0, 1)
	fmt.Println("刪除邊 1-3 後,圖為")
	graph.print()

	/* 新增頂點 */
	graph.addVertex(6)
	fmt.Println("新增頂點 6 後,圖為")
	graph.print()

	/* 刪除頂點 */
	// 頂點 3 的索引為 1
	graph.removeVertex(1)
	fmt.Println("刪除頂點 3 後,圖為")
	graph.print()
}