gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/client/mock/mock_test.go (about)

     1  package mock
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  
     7  	"gitee.com/liuxuezhan/go-micro-v1.18.0/errors"
     8  )
     9  
    10  func TestClient(t *testing.T) {
    11  	type TestResponse struct {
    12  		Param string
    13  	}
    14  
    15  	response := []MockResponse{
    16  		{Endpoint: "Foo.Bar", Response: map[string]interface{}{"foo": "bar"}},
    17  		{Endpoint: "Foo.Struct", Response: &TestResponse{Param: "aparam"}},
    18  		{Endpoint: "Foo.Fail", Error: errors.InternalServerError("go.mock", "failed")},
    19  		{Endpoint: "Foo.Func", Response: func() string { return "string" }},
    20  		{Endpoint: "Foo.FuncStruct", Response: func() *TestResponse { return &TestResponse{Param: "aparam"} }},
    21  		{Endpoint: "Foo.FuncWithReqBody", Response: func(req interface{}) string {
    22  			if req.(map[string]string)["foo"] == "bar" {
    23  				return "string"
    24  			}
    25  			return "wrong"
    26  		}},
    27  	}
    28  
    29  	c := NewClient(Response("go.mock", response))
    30  
    31  	for _, r := range response {
    32  		req := c.NewRequest("go.mock", r.Endpoint, map[string]string{"foo": "bar"})
    33  		var rsp interface{}
    34  
    35  		err := c.Call(context.TODO(), req, &rsp)
    36  
    37  		if err != r.Error {
    38  			t.Fatalf("Expecter error %v got %v", r.Error, err)
    39  		}
    40  
    41  		t.Log(rsp)
    42  		if r.Endpoint == "Foo.FuncWithReqBody" {
    43  			req := c.NewRequest("go.mock", r.Endpoint, map[string]string{"foo": "wrong"})
    44  			var rsp interface{}
    45  
    46  			err := c.Call(context.TODO(), req, &rsp)
    47  
    48  			if err != r.Error {
    49  				t.Fatalf("Expecter error %v got %v", r.Error, err)
    50  			}
    51  			if rsp.(string) != "wrong" {
    52  				t.Fatalf("Expecter response 'wrong' got %v", rsp)
    53  			}
    54  			t.Log(rsp)
    55  		}
    56  	}
    57  
    58  }