unit-testinggomockingstub

Go: mock return value of a function in unit test


I have 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 would like to create a small unit test for each function. For "main()", I want to mock the return value of function "foo()", because I won't test "foo()", but the rest of main()-code.

I'm looking for an easy way to stub/mock the return value. I just found mocks with struct or interaces etc. But I didn't use these elements in 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://go.dev/play/p/a0SudgaRCnu

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

    Use the Go testing package to unit test the side function. You might also unit test the isEven function directly. The main function should not contain any code that you want to unit test.

    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)
        }
    }