Home >Backend Development >Golang >Go: Mock return value of function in unit test

Go: Mock return value of function in unit test

王林
王林forward
2024-02-09 23:39:091252browse

Go: Mock return value of function in unit test

In software development, unit testing is a very important task, which can help developers ensure the quality and reliability of the code. In the Go language, we can use some libraries and technologies to simulate the return value of a function for better unit testing. In this article, PHP editor Xiaoxin will introduce to you the method of implementing function simulation return values ​​in the Go language to help developers better conduct unit testing and improve the quality and maintainability of the code.

Question content

I created a small script in golang (my first golang project).

Example:

package main

import (
    "fmt"
    "math/rand"
)

func main() {
    i := rand.Intn(10)
    foo := foo(i)

    if foo {
        fmt.Printf("%d is even!", i)
        // more code ... 
    } else {
        fmt.Printf("%d is odd!", i)
        // more code ... 
    }
}

func foo(i int) bool {
    if i%2 == 0 {
        return true
    } else {
        return false
    }
}

I want to create a small unit test for each function. For "main()" I want to mock the return value of function "foo()" since I won't be testing "foo()" but the rest of the main() code.

I'm looking for a simple way to stub/mock return values. I just discovered mocking with structures or interfaces etc. But I'm not using these elements in the code (it's a simple project).

Solution

Use a realistic, minimal, reproducible example: How to create a minimal, reproducible example.

For example, in go,

package main

import (
    "fmt"
    "math/rand"
)

func iseven(i int) bool {
    return i%2 == 0
}

func side(n int) string {
    if iseven(n) {
        return "right"
    } else {
        return "left"
    }
}

func main() {
    n := 1 + rand.intn(10)
    hand := side(n)
    fmt.printf("number %d is on the %s-hand side of the street.\n", n, hand)
}

https://www.php.cn/link/7c63a554c36ea63c77723a472b7ca20f

number 9 is on the left-hand side of the street.

Use go test package to unit test the side function. You can also unit test the iseven function directly. main The function should not contain any code to be unit tested.

package main

import (
    "testing"
)

func TestSide(t *testing.T) {
    n := 7
    got := side(n)
    want := "left"
    if got != want {
        t.Errorf("side(%d) = %s; want %s", n, got, want)
    }
}

The above is the detailed content of Go: Mock return value of function in unit test. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete