Merge pull request #466 from Ak-Army/master

send requestBody to mock function if it can handle it
This commit is contained in:
Asim Aslam 2019-05-07 14:16:04 +01:00 committed by GitHub
commit dc2e150a58
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 2 deletions

View File

@ -83,7 +83,11 @@ func (m *MockClient) Call(ctx context.Context, req client.Request, rsp interface
}
response := r.Response
if t := reflect.TypeOf(r.Response); t.Kind() == reflect.Func {
response = reflect.ValueOf(r.Response).Call([]reflect.Value{})[0].Interface()
var request []reflect.Value
if t.NumIn() == 1 {
request = append(request, reflect.ValueOf(req.Body()))
}
response = reflect.ValueOf(r.Response).Call(request)[0].Interface()
}
v.Set(reflect.ValueOf(response))

View File

@ -18,12 +18,18 @@ func TestClient(t *testing.T) {
{Endpoint: "Foo.Fail", Error: errors.InternalServerError("go.mock", "failed")},
{Endpoint: "Foo.Func", Response: func() string { return "string" }},
{Endpoint: "Foo.FuncStruct", Response: func() *TestResponse { return &TestResponse{Param: "aparam"} }},
{Endpoint: "Foo.FuncWithReqBody", Response: func(req interface{}) string {
if req.(map[string]string)["foo"] == "bar" {
return "string"
}
return "wrong"
}},
}
c := NewClient(Response("go.mock", response))
for _, r := range response {
req := c.NewRequest("go.mock", r.Endpoint, map[string]interface{}{"foo": "bar"})
req := c.NewRequest("go.mock", r.Endpoint, map[string]string{"foo": "bar"})
var rsp interface{}
err := c.Call(context.TODO(), req, &rsp)
@ -33,6 +39,20 @@ func TestClient(t *testing.T) {
}
t.Log(rsp)
if r.Endpoint == "Foo.FuncWithReqBody" {
req := c.NewRequest("go.mock", r.Endpoint, map[string]string{"foo": "wrong"})
var rsp interface{}
err := c.Call(context.TODO(), req, &rsp)
if err != r.Error {
t.Fatalf("Expecter error %v got %v", r.Error, err)
}
if rsp.(string) != "wrong" {
t.Fatalf("Expecter response 'wrong' got %v", rsp)
}
t.Log(rsp)
}
}
}