Until now you checked your shop by hand: send a request, read the answer, decide if it's right. A test is code that does this for you, every time you run it, so you notice at once when a change breaks something.
In this course, tests live in a type that embeds Suite, a small test kit given to you before your code. Each method whose name starts with Test is one test, and s.Equal(expected, actual) checks that two values are equal: if they differ, the test fails and shows both. Here is a test for a small function, not for the shop:
func addShipping(price int) int {
return price + 5
}
type ShippingTests struct {
Suite
}
func (s *ShippingTests) TestAddShipping() {
s.Equal(15, addShipping(10))
}
To send requests, a test starts its own test server: httptest.NewServer(app) runs the app on a free local port, server.URL is its address, and defer server.Close() stops it when the test ends. http.Get(server.URL + "/products") sends a GET and gives back the response, with the status in response.StatusCode. The shop is loaded for you as app, and it answers GET /products with 200 and its four products. The check runs your test on the shop, then on a broken copy that lost its GET /products route, and must print:
Your tests on the shop:
TestProductsAnswer200 ... ok
1 test: OK
Your tests on a copy that lost its GET /products route:
TestProductsAnswer200 ... FAIL
Not equal: expected 200, actual 405
1 test: 1 failed, so they caught this bug
Your task: write the type ProductTests, which embeds Suite, with one test method, TestProductsAnswer200, that starts a test server for app, sends GET /products and checks that the status code is 200.
Assignment
Follow the Coding Tutorial to write your first test: a type, a test method, a test server, a request and one check.
Hint
In s.Equal, put what you expect first and what you got second. Go won't compile a variable you never use, so the code runs again once the check reads response. A test with no check passes on any shop, even a broken one.
Free plan: 30 tutor messages. PRO is unlimited.
