Home  >  Article  >  Backend Development  >  How Can You Test Unexported Functions in Go?

How Can You Test Unexported Functions in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 05:47:02877browse

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.

<code class="go">// 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
}</code>

Black-box testing (in example_test.go):

<code class="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()
        }
    }
}</code>

White-box testing (in example_internal_test.go):

<code class="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()
        }
    }
}</code>

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.

The above is the detailed content of How Can You Test Unexported Functions in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn