"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can You Test Unexported Functions in Go?

How Can You Test Unexported Functions in Go?

Published on 2024-11-06
Browse:684

How Can You Test Unexported Functions in Go?

Calling Test Functions from Non-Test Go Files

In Go, testing functions should not be called from within the code itself. Instead, unit tests are meant to be executed using the go test command.

Black and White Box Testing

Go supports two types of unit testing: black-box and white-box.

Black-box testing tests exported functions from outside the package, simulating how external packages will interact with it.

White-box testing tests unexported functions from within the package itself.

Example

Consider a package called example with an exported function Sum and an unexported utility function add.

// example.go
package example

func Sum(nums ...int) int {
    sum := 0
    for _, num := range nums {
        sum = add(sum, num)
    }
    return sum
}

func add(a, b int) int {
    return a   b
}

Black-box testing (in example_test.go):

package example_test

import (
    "testing"

    "example"
)

func TestSum(t *testing.T) {
    tests := []struct {
        nums []int
        sum  int
    }{
        {nums: []int{1, 2, 3}, sum: 6},
        {nums: []int{2, 3, 4}, sum: 9},
    }

    for _, test := range tests {
        s := example.Sum(test.nums...)
        if s != test.sum {
            t.FailNow()
        }
    }
}

White-box testing (in example_internal_test.go):

package example

import "testing"

func TestAdd(t *testing.T) {
    tests := []struct {
        a   int
        b   int
        sum int
    }{
        {a: 1, b: 2, sum: 3},
        {a: 3, b: 4, sum: 7},
    }

    for _, test := range tests {
        s := add(test.a, test.b)
        if s != test.sum {
            t.FailNow()
        }
    }
}

In summary, unit tests should be executed using the go test command, and never called directly from within code. Black and white-box testing provide different levels of access to the package's implementation for testing purposes.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3