Last active
June 1, 2016 03:21
-
-
Save jochasinga/9feb82a376ddacf4f2e216fe49e0b583 to your computer and use it in GitHub Desktop.
Dependency injection in unit testing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package di | |
import ( | |
"bytes" | |
"io" | |
"testing" | |
) | |
// Watcher takes an io.Writer as an attribute | |
type Watcher struct { | |
Writer io.Writer | |
} | |
// Notify write a string to the io.Writer | |
func (w *Watcher) Notify(msg string) error { | |
_, err := w.Writer.Write([]byte(msg)) | |
if err != nil { | |
return err | |
} | |
return nil | |
} | |
// Howler takes a string as its attribute | |
type Howler struct { | |
Message string | |
} | |
// NotifyTo write a string to the given io.Writer | |
func (h *Howler) NotifyTo(w io.Writer) error { | |
_, err := w.Write([]byte(h.Message)) | |
if err != nil { | |
return err | |
} | |
return nil | |
} | |
// Create a simple mock of io.Writer | |
type MockWriter struct { | |
Called bool | |
Data []byte | |
} | |
func (mw *MockWriter) Write(data []byte) (int, error) { | |
mw.Called = true | |
mw.Data = data | |
return 0, nil | |
} | |
var ( | |
// The two "writers" we want to test | |
buf = new(bytes.Buffer) | |
mock = new(MockWriter) | |
) | |
func TestWatcherAgainstBuffer(t *testing.T) { | |
// inject buffer as a constructor dependency | |
watcher := &Watcher{ Writer: buf } | |
_ = watcher.Notify("Alert") | |
result := buf.Next(len("Alert")) | |
if bytes.Compare(result, []byte("Alert")) != 0 { | |
t.Error("Bummer!") | |
} | |
} | |
func TestHowlerAgainstMockWriter(t *testing.T) { | |
howler := &Howler{ Message: "Warning" } | |
// inject MockWriter as a method dependency | |
_ = howler.NotifyTo(mock) | |
if !mock.Called || bytes.Compare(mock.Data, []byte("Warning")) != 0 { | |
t.Error("Dang!") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment