Last active
August 29, 2015 14:11
-
-
Save partkyle/a49c8a5f7c8e63054494 to your computer and use it in GitHub Desktop.
setup / teardown pattern in Go tests
This file contains hidden or 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 main_test | |
| import ( | |
| "net/http/httptest" | |
| "testing" | |
| ) | |
| type testHarness struct { | |
| server *httptest.Server | |
| } | |
| func setup() *testHarness { | |
| return &testHarness{server: httptest.NewServer(handler)} | |
| } | |
| func (t *testHarness) teardown() { | |
| t.server.Close() | |
| } | |
| func TestSomething(t *testing.T) { | |
| h := setup() | |
| defer h.teardown() | |
| t.Log(h.server.URL) | |
| } | |
| func TestSomethingElse(t *testing.T) { | |
| h := setup() | |
| defer h.teardown() | |
| t.Log(h.server.URL) | |
| } |
This file contains hidden or 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 main_test | |
| import ( | |
| "net/http/httptest" | |
| "testing" | |
| ) | |
| var ( | |
| server *httptest.Server | |
| ) | |
| func setup() { | |
| // should actually be my http handler that I am testing | |
| server = httptest.NewServer(nil) | |
| } | |
| func teardown() { | |
| server.Close() | |
| } | |
| func TestSomething(t *testing.T) { | |
| setup() | |
| defer teardown() | |
| t.Log(server.URL) | |
| } | |
| func TestSomethingElse(t *testing.T) { | |
| setup() | |
| defer teardown() | |
| t.Log(server.URL) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment