@@ -22,6 +22,35 @@ func assertEquality(t *testing.T, obj1 any, obj2 any) {
22
22
}
23
23
}
24
24
25
+ func mockServer (t * testing.T ) * httptest.Server {
26
+ t .Helper ()
27
+ return httptest .NewServer (http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
28
+ currentTime := time .Now ()
29
+ formattedTime := currentTime .Format (time .ANSIC )
30
+
31
+ if strings .Contains (r .Header .Get ("content-type" ), "text/plain" ) {
32
+
33
+ w .Header ().Set ("Content-Type" , "text/plain" )
34
+ fmt .Fprint (w , formattedTime )
35
+
36
+ } else if strings .Contains (r .Header .Get ("content-type" ), "application/json" ) {
37
+
38
+ w .Header ().Set ("Content-Type" , "application/json" )
39
+
40
+ timeJson , err := json .Marshal (formattedTime )
41
+ if err != nil {
42
+ log .Fatalf ("error converting to json: %v" , err )
43
+ }
44
+ _ , err = w .Write (timeJson )
45
+ if err != nil {
46
+ log .Fatalf ("error writing data to response: %v" , err )
47
+ }
48
+ } else {
49
+ http .Error (w , http .StatusText (http .StatusUnsupportedMediaType ), http .StatusUnsupportedMediaType )
50
+ }
51
+ }))
52
+ }
53
+
25
54
func TestGetTime (t * testing.T ) {
26
55
formattedTime := time .Now ().Format (time .ANSIC )
27
56
expectedTime , err := time .Parse (time .ANSIC , formattedTime )
@@ -141,31 +170,7 @@ func TestGetTimeMock(t *testing.T) {
141
170
}
142
171
for _ , testcase := range testcases {
143
172
t .Run (testcase .name , func (t * testing.T ) {
144
- mockServer := httptest .NewServer (http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
145
- currentTime := time .Now ()
146
- formattedTime := currentTime .Format (time .ANSIC )
147
-
148
- if strings .Contains (r .Header .Get ("content-type" ), "text/plain" ) {
149
-
150
- w .Header ().Set ("Content-Type" , "text/plain" )
151
- fmt .Fprint (w , formattedTime )
152
-
153
- } else if strings .Contains (r .Header .Get ("content-type" ), "application/json" ) {
154
-
155
- w .Header ().Set ("Content-Type" , "application/json" )
156
-
157
- timeJson , err := json .Marshal (formattedTime )
158
- if err != nil {
159
- log .Fatalf ("error converting to json: %v" , err )
160
- }
161
- _ , err = w .Write (timeJson )
162
- if err != nil {
163
- log .Fatalf ("error writing data to response: %v" , err )
164
- }
165
- } else {
166
- http .Error (w , http .StatusText (http .StatusUnsupportedMediaType ), http .StatusUnsupportedMediaType )
167
- }
168
- }))
173
+ mockServer := mockServer (t )
169
174
170
175
defer mockServer .Close ()
171
176
0 commit comments