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
Release: 2025-01-02 18:57:37
Original
246 people have browsed it

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()
    ... 
}
Copy after login

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()
    // ...
}
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template