Back to Repositories

Testing Graph Adjacency Matrix 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. The tests verify vertex and edge management functionality while ensuring proper graph state maintenance.

Test Coverage Overview

The test suite provides comprehensive coverage of graph operations including initialization, edge management, and vertex modifications.

  • Tests graph initialization with predefined vertices and edges
  • Validates edge addition and removal operations
  • Verifies vertex addition and deletion functionality
  • Ensures proper graph state after each operation

Implementation Analysis

The testing approach utilizes Go’s built-in testing framework to validate graph operations through a sequence of modifications.

The test implements a step-by-step verification process, using the testing.T struct for test execution and fmt for output validation. Each operation is followed by a graph state print to verify the correctness of modifications.

Technical Details

  • Testing Framework: Go’s native testing package
  • Print Verification: fmt package for output validation
  • Test Structure: Single comprehensive test function (TestGraphAdjMat)
  • Graph Implementation: Adjacency matrix representation

Best Practices Demonstrated

The test implementation showcases several testing best practices in Go.

  • Clear test function naming following Go conventions
  • Systematic operation verification
  • Comprehensive state validation after each modification
  • Well-structured test flow with clear operation separation

krahets/hello-algo

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()
}