Home >Backend Development >Golang >How Can I Mock External Functions in Go for Unit Testing?

How Can I Mock External Functions in Go for Unit Testing?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-02 18:57:37220browse

How Can I Mock External Functions in Go for Unit Testing?

Mocking External Functions in Go

When testing functions that rely on external packages, mocking those external functions can be essential for creating isolated and reliable tests. Consider the following example:

import x.y.z

func abc() {
    ...
    v := z.SomeFunc()
    ... 
}

Can we mock z.SomeFunc() to unit test abc()?

Solution: Refactoring and Mocking

Yes, mocking z.SomeFunc() is possible with a simple refactoring. Introduce a variable zSomeFunc of function type and initialize it with z.SomeFunc. Then, within your function that calls z.SomeFunc(), invoke zSomeFunc() instead:

var zSomeFunc = z.SomeFunc

func abc() {
    // ...
    v := zSomeFunc()
    // ...
}

During tests, assign a custom function to zSomeFunc that returns the desired test behavior. For instance:

func TestAbc(t *testing.T) {
    // Save current function and restore at the end:
    old := zSomeFunc
    defer func() { zSomeFunc = old }()

    zSomeFunc = func() int {
        // This will be called, do whatever you want to,
        // return whatever you want to
        return 1
    }

    // Call the tested function
    abc()

    // Check expected behavior
}

The above is the detailed content of How Can I Mock External Functions in Go for Unit Testing?. 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