@@ -2,6 +2,10 @@ package main
2
2
3
3
import (
4
4
"errors"
5
+ "fmt"
6
+ "io/ioutil"
7
+ "net/http"
8
+ "net/http/httptest"
5
9
"testing"
6
10
)
7
11
@@ -20,9 +24,45 @@ func (tms TransactionReaderStub) ReadBalance(account int) (int, error) {
20
24
}
21
25
22
26
func TestBalanceEndpoint (t * testing.T ) {
27
+ req := httptest .NewRequest (http .MethodGet , "localhost:8080/balance?account=12" , nil )
28
+ rec := httptest .NewRecorder ()
23
29
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
+ }
24
48
}
25
49
26
50
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
+ }
27
58
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
+ }
28
68
}
0 commit comments