Skip to content

Commit 30395c8

Browse files
committed
[+] add TestNoPostsReturned() to blog example
1 parent 558cc24 commit 30395c8

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

examples/blog/blog_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,3 +101,31 @@ func TestShouldRespondWithErrorOnFailure(t *testing.T) {
101101
t.Errorf("there were unfulfilled expectations: %s", err)
102102
}
103103
}
104+
105+
func TestNoPostsReturned(t *testing.T) {
106+
mock, err := pgxmock.NewConn()
107+
if err != nil {
108+
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
109+
}
110+
defer mock.Close(context.Background())
111+
112+
// create app with mocked db, request and response to test
113+
app := &api{mock}
114+
req, err := http.NewRequest("GET", "http://localhost/posts", nil)
115+
if err != nil {
116+
t.Fatalf("an error '%s' was not expected while creating request", err)
117+
}
118+
w := httptest.NewRecorder()
119+
120+
mock.ExpectQuery("^SELECT (.+) FROM posts$").WillReturnRows(mock.NewRows([]string{"id", "title", "body"}))
121+
// now we execute our request
122+
app.posts(w, req)
123+
if w.Code != 200 {
124+
t.Fatalf("expected status code to be 200, but got: %d\nBody: %v", w.Code, w.Body)
125+
}
126+
127+
// we make sure that all expectations were met
128+
if err := mock.ExpectationsWereMet(); err != nil {
129+
t.Errorf("there were unfulfilled expectations: %s", err)
130+
}
131+
}

0 commit comments

Comments
 (0)