Back to Repositories

Testing Binary Search Recursive Implementation in hello-algo

This test suite validates the binary search recursive implementation in Go, focusing on both successful and unsuccessful search scenarios. The tests verify the algorithm’s ability to find target elements in a sorted array and handle cases where the target is not present.

Test Coverage Overview

The test coverage encompasses core binary search functionality, testing both successful target element location and handling of non-existent elements.

  • Tests successful search with target element 6
  • Validates behavior with non-existent target (99)
  • Verifies index return values for both scenarios

Implementation Analysis

The testing approach utilizes Go’s native testing framework with a single comprehensive test case that validates multiple scenarios. The implementation follows Go’s testing conventions, using the testing.T struct for test execution and fmt for output verification.

  • Uses Go’s testing package for test structure
  • Implements direct assertion testing
  • Utilizes fmt.Println for result visualization

Technical Details

  • Testing Framework: Go testing package
  • Test Runner: go test
  • Output Handler: fmt package
  • Test Data: Pre-defined sorted integer slice
  • Assertion Method: Direct comparison

Best Practices Demonstrated

The test implementation showcases clean and efficient testing practices in Go, with clear test case organization and proper use of the testing framework.

  • Clear test function naming
  • Organized test data setup
  • Multiple scenario coverage in single test
  • Proper use of testing.T parameter
  • Clear output formatting

krahets/hello-algo

zh-hant/codes/go/chapter_divide_and_conquer/binary_search_recur_test.go

            
// File: binary_search_recur_test.go
// Created Time: 2023-07-19
// Author: hongyun-robot ([email protected])

package chapter_divide_and_conquer

import (
	"fmt"
	"testing"
)

func TestBinarySearch(t *testing.T) {
	nums := []int{1, 3, 6, 8, 12, 15, 23, 26, 31, 35}
	target := 6
	noTarget := 99
	targetIndex := binarySearch(nums, target)
	fmt.Println("目標元素 6 的索引 = ", targetIndex)
	noTargetIndex := binarySearch(nums, noTarget)
	fmt.Println("不存在目標元素的索引 = ", noTargetIndex)
}