11// Sample test to show how to mock an HTTP GET call internally.
2+ // Differs slightly from the book to show more.
23package listing03
34
45import (
@@ -28,6 +29,17 @@ var feed = `<?xml version="1.0" encoding="UTF-8"?>
2829</channel>
2930</rss>`
3031
32+ // mockServer returns a pointer to a server to handle the get call.
33+ func mockServer () * httptest.Server {
34+ f := func (w http.ResponseWriter , r * http.Request ) {
35+ w .WriteHeader (200 )
36+ w .Header ().Set ("Content-Type" , "application/xml" )
37+ fmt .Fprintln (w , feed )
38+ }
39+
40+ return httptest .NewServer (http .HandlerFunc (f ))
41+ }
42+
3143// Item defines the fields associated with the item tag in
3244// the buoy RSS document.
3345type Item struct {
@@ -55,21 +67,10 @@ type Document struct {
5567 URI string
5668}
5769
58- // mockServer returns a pointer to a server to handle the mock get call.
59- func mockServer () * httptest.Server {
60- f := func (w http.ResponseWriter , r * http.Request ) {
61- w .WriteHeader (200 )
62- w .Header ().Set ("Content-Type" , "application/xml" )
63- fmt .Fprintln (w , feed )
64- }
65-
66- return httptest .NewServer (http .HandlerFunc (f ))
67- }
68-
69- // TestDownload validates the http Get function can download content and
70- // the content can be unmarshaled and clean.
70+ // TestDownload validates the http Get function can download content
71+ // and the content can be unmarshaled and clean.
7172func TestDownload (t * testing.T ) {
72- statusCode := 200
73+ statusCode := http . StatusOK
7374
7475 server := mockServer ()
7576 defer server .Close ()
@@ -90,10 +91,10 @@ func TestDownload(t *testing.T) {
9091 defer resp .Body .Close ()
9192
9293 if resp .StatusCode != statusCode {
93- t .Fatalf ("\t \t Should receive a \" %d\" status code . %v %v" ,
94+ t .Fatalf ("\t \t Should receive a \" %d\" status. %v %v" ,
9495 statusCode , ballotX , resp .StatusCode )
9596 }
96- t .Logf ("\t \t Should receive a \" %d\" status code . %v" ,
97+ t .Logf ("\t \t Should receive a \" %d\" status. %v" ,
9798 statusCode , checkMark )
9899
99100 var d Document
0 commit comments