-3

I've read a bunch about this and don't understand why mocking is so complicated in Go. Is there a simple way to mock just one function?

For example:

func addB(num int) int {
  return b() + num;
}

func getB() int {
  return 3;
}

If I want to test addB but change getB to respond with 6 or something instead, in other languages I'd write a unit test like:

expect(getB).toBeCalled.andRespond(5);
assertEqual(addB(2), 7);

I don't see a way to do the mocking in Go without creating an object with getB as one of its methods, creating an interface for that object, and then including a test interface sent with addB. Is that really the best way to do it?

1 Answers1

0

You can declare a function as a variable and inject a mock implementation for the tests.

Example:

package main

import "fmt"

var getB = func() int {
    return 3
}

func main() {
    fmt.Println(getB())

    getB = func() int {
        return 5
    }

    fmt.Println(getB())
}
serge-v
  • 750
  • 2
  • 8
  • Although this works, but it will fail when running tests in parallel. Also, modifying a global variable from another file makes me uncomfortable. Not sure if there is any other way though . – Somil Bhandari Aug 18 '22 at 10:28