@@ -19,17 +19,15 @@ import (
19
19
"google.golang.org/api/option"
20
20
)
21
21
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 {
27
25
28
26
ctx := context .Background ()
29
27
client , err := initFirestore (ctx )
30
28
31
29
if err != nil {
32
- t .Fatalf ("failed to initialize Firestore: %v" , err )
30
+ log .Fatalf ("failed to initialize Firestore: %v" , err )
33
31
}
34
32
35
33
return & handlers.Service {Client : client }
@@ -51,8 +49,18 @@ func initFirestore(ctx context.Context) (*firestore.Client, error) {
51
49
return client , nil
52
50
}
53
51
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
+
54
63
func Test_Read (t * testing.T ) {
55
- service := createService (t )
56
64
res := httptest .NewRecorder ()
57
65
58
66
// adds chi context
@@ -69,3 +77,21 @@ func Test_Read(t *testing.T) {
69
77
t .Fatalf ("expected status code 200 but got %v" , res .Result ())
70
78
}
71
79
}
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