Inject testable dependencies
Inject testable dependencies
Dependency injection means supplying a required collaborator instead of constructing it inside the consumer. A small interface lets the consumer accept a real implementation or a controlled test substitute. This makes behavior testable without requiring a network, database or external service. Use interfaces only where substitution is useful.
package main
import ( "fmt")
type Names interface{ Find(int) (string, bool) }type Memory map[int]string
func (m Memory) Find(id int) (string, bool) { s, ok := m[id]; return s, ok }func greeting(n Names, id int) string { s, ok := n.Find(id) if !ok { return "unknown" } return "Hello, " + s}func main() { m := Memory{1: "Ada"} fmt.Println(greeting(m, 1)) fmt.Println(greeting(m, 2))}greeting depends on the lookup behavior, not on how names are stored. Memory provides a deterministic implementation with a map. The bool explicitly reports whether the ID exists. A real external provider may also need to represent failures with error returns.
Expected output:
Hello, AdaunknownCheck calls with a test substitute
package main
import ( "fmt")
type Sender interface{ Send(string) }type Recorder struct{ Messages []string }
func (r *Recorder) Send(s string) { r.Messages = append(r.Messages, s) }func notify(s Sender) { s.Send("ready") }func main() { r := &Recorder{} notify(r) fmt.Println(len(r.Messages), r.Messages[0])}Recorder captures the message instead of sending it externally. The output checks count and content. This is a standalone demonstration, not yet a go test suite. Later testing lessons cover assertions, errors and richer substitutes. The interface contract here is synchronous and has no failure result.
Expected output:
1 readyTry it locally
Define RateSource with Rate() int and FixedRate implementing it. Write cost(s RateSource,units int) int using multiplication. Print the cost for rate 4 and 3 units, then rate 2 and 3 units.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Interfaces 09: Inject testable dependencies
Check the lesson objective before moving on.
What makes greeting easy to test in the example?
What does Recorder verify in the notification demonstration?