@@ -17,33 +17,58 @@ type JsonResponseAsserter[T any] struct {
1717}
1818
1919func (j JsonResponseAsserter [T ]) Assert (t * testing.T , context * Context , stepContext * Context ) error {
20+ actualBody , res , err := extractBody [T ](t , stepContext )
21+ if err != nil {
22+ return err
23+ }
24+
25+ expectedBody := j .ExpectedBody
26+ if j .ExpectedBodyFunc != nil {
27+ expectedBody = j .ExpectedBodyFunc (context )
28+ }
29+
30+ AssertEqual (t , expectedBody , actualBody )
31+ AssertEqual (t , j .ExpectedStatusCode , res .StatusCode )
32+
33+ return nil
34+ }
35+
36+ var _ Asserter = JsonFuncAsserter [string ]{}
37+
38+ type JsonFuncAsserter [T any ] struct {
39+ ExpectedFunc func (ctx * Context , body T )
40+ ExpectedStatusCode int
41+ }
42+
43+ func (j JsonFuncAsserter [T ]) Assert (t * testing.T , context * Context , stepContext * Context ) error {
44+ actualBody , res , err := extractBody [T ](t , stepContext )
45+ if err != nil {
46+ return err
47+ }
48+ j .ExpectedFunc (context , actualBody )
49+ AssertEqual (t , j .ExpectedStatusCode , res .StatusCode )
50+ return nil
51+ }
52+
53+ func extractBody [T any ](t * testing.T , stepContext * Context ) (T , * http.Response , error ) {
54+ var actualBody T
2055 res , ok := ContextGet [* http.Response ](stepContext , "response" )
2156 if ! ok {
2257 t .Error ("no response in context" )
23- return errors .New ("no response in context" )
58+ return actualBody , res , errors .New ("no response in context" )
2459 }
2560
2661 b , err := io .ReadAll (res .Body )
2762 if err != nil {
2863 t .Error (err )
29- return err
64+ return actualBody , res , err
3065 }
3166
32- var actualBody T
3367 t .Logf ("response body: %s" , string (b ))
3468 err = json .Unmarshal (b , & actualBody )
3569 if err != nil {
3670 t .Error (err )
37- return err
71+ return actualBody , res , err
3872 }
39-
40- expectedBody := j .ExpectedBody
41- if j .ExpectedBodyFunc != nil {
42- expectedBody = j .ExpectedBodyFunc (context )
43- }
44-
45- AssertEqual (t , expectedBody , actualBody )
46- AssertEqual (t , j .ExpectedStatusCode , res .StatusCode )
47-
48- return nil
73+ return actualBody , res , nil
4974}
0 commit comments