github.com/wfusion/gofusion@v1.1.14/test/http/cases/client_test.go (about)

     1  package cases
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  	"testing"
     7  
     8  	"github.com/jarcoal/httpmock"
     9  	"github.com/stretchr/testify/suite"
    10  
    11  	"github.com/wfusion/gofusion/log"
    12  
    13  	fusHtp "github.com/wfusion/gofusion/http"
    14  	testHtp "github.com/wfusion/gofusion/test/http"
    15  )
    16  
    17  func TestClient(t *testing.T) {
    18  	testingSuite := &Client{Test: new(testHtp.Test)}
    19  	testingSuite.Init(testingSuite)
    20  	suite.Run(t, testingSuite)
    21  }
    22  
    23  type Client struct {
    24  	*testHtp.Test
    25  }
    26  
    27  func (t *Client) BeforeTest(suiteName, testName string) {
    28  	t.Catch(func() {
    29  		log.Info(context.Background(), "right before %s %s", suiteName, testName)
    30  
    31  		httpmock.Activate()
    32  	})
    33  }
    34  
    35  func (t *Client) AfterTest(suiteName, testName string) {
    36  	t.Catch(func() {
    37  		log.Info(context.Background(), "right after %s %s", suiteName, testName)
    38  
    39  		httpmock.DeactivateAndReset()
    40  	})
    41  }
    42  
    43  func (t *Client) TestMock() {
    44  	t.Catch(func() {
    45  		// Given
    46  		fakeUrl := "http://localhost/TestMock"
    47  		expected := &fusHtp.Response{
    48  			Code:    0,
    49  			Message: "ok",
    50  			Data:    2,
    51  		}
    52  		actual := new(fusHtp.Response)
    53  		responder, err := httpmock.NewJsonResponder(http.StatusOK, expected)
    54  		t.NoError(err)
    55  		httpmock.RegisterResponder(http.MethodGet, fakeUrl, responder)
    56  		cli := fusHtp.NewRequest(context.Background(), fusHtp.AppName(t.AppName())).SetResult(&actual)
    57  
    58  		// When
    59  		rsp, err := cli.Get(fakeUrl)
    60  
    61  		// Then
    62  		t.NoError(err)
    63  		t.Equal(http.StatusOK, rsp.StatusCode())
    64  		t.EqualValues(expected.Data, actual.Data)
    65  	})
    66  }