Testing
A key works with any number of containers, and finds in each the service registered there. So code that takes its services from a container can be tested with fakes: register them under the same keys, in a container the test makes for itself.
var c gocontainer.ContainerUsers.Register(&c, downUsers{}) // a fake whose every call fails
h := routes(&c) // built with the fakeEach test gets a fresh container, so tests don’t see each other’s fakes and can run in parallel. There is no global container to reset.
Fakes need interface keys
Section titled “Fakes need interface keys”A fake can only go in under a key whose type it fits. Give the services you’ll fake an interface key, such as
Key[Users]; a key for a concrete type, such as Key[*SQLUsers], only takes that type.
Example: an HTTP server
Section titled “Example: an HTTP server”The server’s handler takes its user store from a container. main registers the real store:
// Command server serves users' names over HTTP. Its handler takes the user store from a container,// so a test can hand it a fake.//// go run ./examples/server// curl localhost:8080/users/1package main
import ( "context" "errors" "fmt" "log" "net/http"
"github.com/vardius/gocontainer/v2")
// ErrNotFound is what Users returns for an id it doesn't know.var ErrNotFound = errors.New("user not found")
// Users looks up a user's name by id.type Users interface { Name(ctx context.Context, id string) (string, error)}
var usersKey = gocontainer.NewKey[Users]("users")
// routes returns the app's handler, built from the services in c.func routes(c *gocontainer.Container) http.Handler { users := usersKey.MustGet(c)
mux := http.NewServeMux() mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) { name, err := users.Name(r.Context(), r.PathValue("id")) if errors.Is(err, ErrNotFound) { http.NotFound(w, r) return } if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } fmt.Fprintln(w, name) }) return mux}
// staticUsers is the Users the server runs with: a fixed list.type staticUsers map[string]string
func (s staticUsers) Name(_ context.Context, id string) (string, error) { name, ok := s[id] if !ok { return "", ErrNotFound } return name, nil}
func main() { var c gocontainer.Container usersKey.Register(&c, staticUsers{"1": "Ada", "2": "Grace"})
log.Fatal(http.ListenAndServe("localhost:8080", routes(&c)))}The test registers a different store for each case, including a fake whose database is down, and checks what the handler answers:
package main
import ( "context" "errors" "net/http" "net/http/httptest" "testing"
"github.com/vardius/gocontainer/v2")
// downUsers is a fake whose database is unreachable.type downUsers struct{}
func (downUsers) Name(context.Context, string) (string, error) { return "", errors.New("database is down")}
func TestRoutes(t *testing.T) { tests := []struct { name string users Users wantCode int wantBody string }{ {"found", staticUsers{"1": "Ada"}, http.StatusOK, "Ada\n"}, {"not found", staticUsers{}, http.StatusNotFound, "404 page not found\n"}, {"store down", downUsers{}, http.StatusInternalServerError, "database is down\n"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Each test registers its own Users, in a container of its own. var c gocontainer.Container usersKey.Register(&c, tt.users)
w := httptest.NewRecorder() routes(&c).ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/users/1", nil))
if w.Code != tt.wantCode || w.Body.String() != tt.wantBody { t.Errorf("GET /users/1 = %d %q, want %d %q", w.Code, w.Body, tt.wantCode, tt.wantBody) } }) }}Run it from a clone of the repository:
go test ./examples/server