Skip to content

Unit Tests in GO

Marc edited this page Feb 25, 2020 · 12 revisions

Let's take a look at two example tests from the authentication microservice tests.

First we look at the file accounts_test.go.

func SetupTests() { mocket.Catcher.Register() db, err := gorm.Open(mocket.DriverName, "connection_string") // Can be any connection string if err != nil { print(err) } DB = db }

Here we have our SetUp function for our tests in this file. Because the accounts model manages database actions, we need a mocked database. For this we use 'mocket'. In the first we register the mocket catcher, which listens for sql querys from our funcions. After this we initialize a grom db instance.

With this setup our tests a good to go!

An example test look like this:

func TestCorrectLogin(t *testing.T) { SetupTests() hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost) testPassword := string(hashedPassword) commonReply := []map[string]interface{}{{"email": "email", "password": testPassword}} mocket.Catcher.Reset().NewMock().WithQuery(SELECT * FROM "accounts" WHERE "accounts"."deleted_at" IS NULL AND ((email = email)) ORDER BY "accounts"."id" ASC LIMIT 1).WithReply(commonReply) result := Login("email", "password") if (result["message"]) != "Logged In" { t.Errorf("Not Logged In correctly! Got '%v'", result["message"]) } }

As you can see from the test name, all tests start with a "Test" and then the what is about to be tested. As a parameter we have "t *testing", which every test needs. Then we call our setup and create a testPassword for our function which is going to be tested. We then create a commonReply, which is the answer our mocked database will provide if our catcher catches a matching sql query. This can be seen in the next line.

After this we declare our result and call our function which we wanna test: Login Internally the Login function calls the database with the exact sql statement we declared in our mocket catcher. We then check if our result has the expected values. If not we call an t.Errorf, which declares the test as failed and print our error message.