Skip to content

Commit d047aa1

Browse files
committed
add test for not found
1 parent fdb4c1a commit d047aa1

File tree

1 file changed

+33
-7
lines changed

1 file changed

+33
-7
lines changed

apps/question-service/tests/read_test.go

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,15 @@ import (
1919
"google.golang.org/api/option"
2020
)
2121

22-
func createService(t testing.TB) *handlers.Service {
23-
err := godotenv.Load(filepath.Join("../", ".env"))
24-
if err != nil {
25-
log.Fatalf("Error loading .env file")
26-
}
22+
var service *handlers.Service
23+
24+
func createService() *handlers.Service {
2725

2826
ctx := context.Background()
2927
client, err := initFirestore(ctx)
3028

3129
if err != nil {
32-
t.Fatalf("failed to initialize Firestore: %v", err)
30+
log.Fatalf("failed to initialize Firestore: %v", err)
3331
}
3432

3533
return &handlers.Service{Client: client}
@@ -51,8 +49,18 @@ func initFirestore(ctx context.Context) (*firestore.Client, error) {
5149
return client, nil
5250
}
5351

52+
func TestMain(m *testing.M) {
53+
err := godotenv.Load(filepath.Join("../", ".env"))
54+
if err != nil {
55+
log.Fatalf("Error loading .env file")
56+
}
57+
service = createService()
58+
defer service.Client.Close()
59+
exitCode := m.Run()
60+
os.Exit(exitCode)
61+
}
62+
5463
func Test_Read(t *testing.T) {
55-
service := createService(t)
5664
res := httptest.NewRecorder()
5765

5866
// adds chi context
@@ -69,3 +77,21 @@ func Test_Read(t *testing.T) {
6977
t.Fatalf("expected status code 200 but got %v", res.Result())
7078
}
7179
}
80+
81+
func Test_ReadNotFound(t *testing.T) {
82+
res := httptest.NewRecorder()
83+
84+
// adds chi context
85+
// https://stackoverflow.com/questions/54580582/testing-chi-routes-w-path-variables
86+
rctx := chi.NewRouteContext()
87+
rctx.URLParams.Add("docRefID", "not-found-docref")
88+
89+
req := httptest.NewRequest(http.MethodGet, "http://localhost:8080/questions/not-found-docref", strings.NewReader(""))
90+
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
91+
92+
service.ReadQuestion(res, req)
93+
94+
if res.Result().StatusCode != 404 {
95+
t.Fatalf("expected status code 404 but got response %v", res.Result())
96+
}
97+
}

0 commit comments

Comments
 (0)