Skip to content

Instantly share code, notes, and snippets.

@musab
Last active March 25, 2022 17:23
Show Gist options
  • Save musab/06a713ecabb82a7b8619d5a7db0761f8 to your computer and use it in GitHub Desktop.
Save musab/06a713ecabb82a7b8619d5a7db0761f8 to your computer and use it in GitHub Desktop.
Go Interfaces and Dependency Injection for Testing
// you can play with the code via https://go.dev/play/p/bVfCe51O0en
package main
import "fmt"
// src/add.go
type Adder interface {
add(int, int) int
}
type AddImpl struct{}
func (a *AddImpl) add(num1, num2 int) int {
return num1 + num2
}
// src/main.go
func main() {
fmt.Println("calling handler")
res := myHandlerThatAlwaysReturns2(&AddImpl{})
fmt.Println("response", res)
// calling tests
// this would typically done via `go test ...` but calling here to see output
HandlerTest()
}
// src/handler.go
func myHandlerThatAlwaysReturns2(adder Adder) int {
return (adder.add(1, 1))
}
// src/handler_test.go
type MockAddImpl struct{}
func (a *MockAddImpl) add(num1, num2 int) int {
// you can return anything here
return num1 - num2
}
func HandlerTest() {
got := myHandlerThatAlwaysReturns2(&MockAddImpl{})
want := 2
if got != want {
fmt.Println("ERROR")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment