| Conditions | 8 |
| Total Lines | 57 |
| Code Lines | 38 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | package http |
||
| 77 | func TestDoWithError(t *testing.T) { |
||
| 78 | originNewRequest := newRequest |
||
| 79 | defer func() { newRequest = originNewRequest }() |
||
| 80 | |||
| 81 | // case 1: mock new http request failed |
||
| 82 | newRequest = func(method, url string, body io.Reader) (*http.Request, error) { |
||
| 83 | return nil, errors.New("new http request failed") |
||
| 84 | } |
||
| 85 | |||
| 86 | req := &Request{ |
||
| 87 | Method: "POST", |
||
| 88 | Protocol: "http", |
||
| 89 | Host: "www.aliyun.com", |
||
| 90 | Path: "/", |
||
| 91 | Form: map[string]string{ |
||
| 92 | "URL": "HI", |
||
| 93 | }, |
||
| 94 | Headers: map[string]string{ |
||
| 95 | "Accept-Language": "zh", |
||
| 96 | }, |
||
| 97 | } |
||
| 98 | _, err := Do(req) |
||
| 99 | assert.EqualError(t, err, "new http request failed") |
||
| 100 | |||
| 101 | // reset new request |
||
| 102 | newRequest = originNewRequest |
||
| 103 | |||
| 104 | // case 2: server error |
||
| 105 | originDo := hookDo |
||
| 106 | defer func() { hookDo = originDo }() |
||
| 107 | hookDo = func(fn do) do { |
||
| 108 | return func(req *http.Request) (res *http.Response, err error) { |
||
| 109 | err = errors.New("mock server error") |
||
| 110 | return |
||
| 111 | } |
||
| 112 | } |
||
| 113 | _, err = Do(req) |
||
| 114 | assert.EqualError(t, err, "mock server error") |
||
| 115 | |||
| 116 | // case 4: mock read response error |
||
| 117 | hookDo = func(fn do) do { |
||
| 118 | return func(req *http.Request) (res *http.Response, err error) { |
||
| 119 | res = &http.Response{ |
||
| 120 | Proto: "HTTP/1.1", |
||
| 121 | ProtoMajor: 1, |
||
| 122 | ProtoMinor: 1, |
||
| 123 | Header: map[string][]string{}, |
||
| 124 | StatusCode: 200, |
||
| 125 | Status: "200 " + http.StatusText(200), |
||
| 126 | } |
||
| 127 | res.Body = ioutil.NopCloser(&errorReader{}) |
||
| 128 | return |
||
| 129 | } |
||
| 130 | } |
||
| 131 | |||
| 132 | _, err = Do(req) |
||
| 133 | assert.EqualError(t, err, "read failed") |
||
| 134 | } |
||
| 190 |