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() ... }
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() // ... }
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 }
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!