Skip to content

Commit 2c6f4df

Browse files
committed
Added tests for http service
1 parent 3181c18 commit 2c6f4df

File tree

2 files changed

+44
-4
lines changed

2 files changed

+44
-4
lines changed

demo_03/bank_test.go

+40
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@ package main
22

33
import (
44
"errors"
5+
"fmt"
6+
"io/ioutil"
7+
"net/http"
8+
"net/http/httptest"
59
"testing"
610
)
711

@@ -20,9 +24,45 @@ func (tms TransactionReaderStub) ReadBalance(account int) (int, error) {
2024
}
2125

2226
func TestBalanceEndpoint(t *testing.T) {
27+
req := httptest.NewRequest(http.MethodGet, "localhost:8080/balance?account=12", nil)
28+
rec := httptest.NewRecorder()
2329

30+
balanceHandler(rec, req)
31+
32+
result := rec.Result()
33+
defer result.Body.Close()
34+
35+
if result.StatusCode != http.StatusOK {
36+
t.Fatalf("Expected status 200, got %v", result.StatusCode)
37+
}
38+
39+
body, err := ioutil.ReadAll(result.Body)
40+
if err != nil {
41+
t.Fatalf("Error reading body")
42+
}
43+
44+
// silly comparison, ideally the body will be parsed, this is just for demonstration purposes
45+
if strBody := string(body); strBody != "10\n" {
46+
t.Fatalf("expected 10, got %s", strBody)
47+
}
2448
}
2549

2650
func TestBalanceEndpointWithTestServer(t *testing.T) {
51+
server := httptest.NewServer(handler())
52+
defer server.Close()
53+
54+
res, err := http.Get(fmt.Sprintf("%s/balance?account=12", server.URL))
55+
if err != nil {
56+
t.Fatalf("an error occured making request to balance endpoint, err: %v", err)
57+
}
2758

59+
body, err := ioutil.ReadAll(res.Body)
60+
if err != nil {
61+
t.Fatalf("Error reading body")
62+
}
63+
64+
// silly comparison, ideally the body will be parsed, this is just for demonstration purposes
65+
if strBody := string(body); strBody != "10\n" {
66+
t.Fatalf("expected 10, got %s", strBody)
67+
}
2868
}

demo_04/bank.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -55,12 +55,12 @@ func (ca ChequingAccount) Balance(tr TransactionReader) (int, error) {
5555
return balance, nil
5656
}
5757

58-
func (ca ChequingAccount) BalanceCAD(url string, tr TransactionReader) (int, error) {
58+
func (ca ChequingAccount) BalanceCAD(baseURL string, tr TransactionReader) (int, error) {
5959
balance, _ := ca.Balance(tr)
60-
if url == "" {
61-
url = "https://api.exchangerate-api.com/v4/latest/usd"
60+
if baseURL == "" {
61+
baseURL = "https://api.exchangerate-api.com/v4"
6262
}
63-
res, err := http.Get(url)
63+
res, err := http.Get(baseURL + "/latest/usd")
6464
if err != nil {
6565
return 0, err
6666
}

0 commit comments

Comments
 (0)