tiaguinho / gosoap

🦉SOAP package for Go
MIT License
507 stars 176 forks source link

Minor refactoring for better testability #58

Closed nij4t closed 4 years ago

nij4t commented 4 years ago

The following PR is aimed to provide a way of testing the library's components without the need of a remote connection. This way the SOAPClient can be created with a custom RoundTripper injected to http.Client which can be used during the unit tests.

// Defining custom round tripper
type RoundTripFunc func(req *http.Request) *http.Response

func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
    return f(req), nil
}

// NewTestClient returns *http.Client
// with Transport replaced to avoid making real calls
func NewTestClient(fn RoundTripFunc) *http.Client {
    return &http.Client{
        Transport: RoundTripFunc(fn),
    }
}

// Creating httpClient with mocked response
fakeclient := NewTestClient(func(req *http.Request) *http.Response {
    return &http.Response{
        StatusCode: 200,
        Body:       ioutil.NopCloser(bytes.NewStringBuffer("Fake document")),
        Header:     make(http.Header),
    }
})

// When sending requests via our client 
// we will get the same response no matter
// what our request object is
res, _ := fakeclient.Get("http://www.example.com")
println(string(res.Body))
// Output: Fake document
tiaguinho commented 4 years ago

Hi @nij4t can you fix the conflicts?