'Mocking just one function in Go [duplicate]
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?
Solution 1:[1]
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())
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | serge-v |
