Last active
April 15, 2021 09:06
-
-
Save Nydan/9f4fad3fa1a052d04a1aafd6d2e785a4 to your computer and use it in GitHub Desktop.
Test case part for integration testing article
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// successLoginTest contains context for the test case. The value of each field is | |
// initialize on setup test case setp and will be the reference for clean up the data on clean(). | |
type successLoginTest struct { | |
id int64 | |
email string | |
pass string | |
} | |
// createVerifiedUser creates a user to be tested for login API. | |
func (s *successLoginTest) createVerifiedUser(e *exampleTestSuite) { | |
row := e.db.QueryRow( | |
`INSERT INTO admin (email, password, status) VALUES ($1, $2, $3) returning id`, | |
s.email, s.pass, "verified") | |
err := row.Scan(&s.id) | |
e.NoError(err, "failed to insert user") | |
} | |
func (s *successLoginTest) loginAPICall(e *exampleTestSuite) *http.Response { | |
c := http.Client{} | |
req, err := http.NewRequest(http.MethodPost, "http://localhost:8080/login", nil) | |
e.NoError(err, "failed to create a request") | |
resp, err := c.Do(req) | |
e.NoError(err, "failed to do request") | |
return resp | |
} | |
// clean cleans predefined data or produced data from the test case. | |
func (s *successLoginTest) clean(e *exampleTestSuite) { | |
_, err := e.db.Exec(`DELETE FROM admin WHERE id = $1`, s.id) | |
e.NoError(err, "failed to delete user") | |
} | |
func (s *successLoginTest) assertLoginSuccessful(e *exampleTestSuite, resp *http.Response) { | |
e.Equal(http.StatusOK, resp.StatusCode, "receive non 200 - OK") | |
buf, err := ioutil.ReadAll(resp.Body) | |
defer resp.Body.Close() | |
e.NoError(err, "failed to read response body") | |
// Do all the assertion related to the response body. | |
e.NotEmpty(buf) | |
} | |
// TestSuccessLogin test case that simulate a registered user try to | |
// login into your app. This test case specifically test your login scenario, | |
// and to test that particular part means we need have a predefined data | |
// which is a verified account. | |
func (e *exampleTestSuite) TestSuccessLogin() { | |
tt := new(successLoginTest) | |
defer tt.clean(e) | |
tt.createVerifiedUser(e) | |
resp := tt.loginAPICall(e) | |
tt.assertLoginSuccessful(e, resp) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment