How to Perform Unit Testing in Gofiber

138 Views Asked by At

I am new to Go lang Programming Now i have to perform Unit testing but after reading several document i am confused how to do it whether go for mocking or just create a dummy database that destroyed when test over.

web.Post("/check-two-factor", authz.RequiresRoles([]string{"admin"}), Controller.CheckTwoFactor(dbpool))


func CheckTwoFactor(dbpool *pgxpool.Pool) fiber.Handler{
    return func(ctx *fiber.Ctx) error {
        userId :=ctx.FormValue("id")
        userID, _ := strconv.Atoi(userId)

        User,err:=FindUserByID(dbpool,int64(userID))
        if err != nil {
            log.Fatalf("Error when finding user by ID: %v", err)
        }
        if !User.Two_factor{
            return ctx.JSON(fiber.Map{
                "result":false,
            })
        }else{
            return ctx.JSON(fiber.Map{
                "result":true,
            })
        }
}
}
1

There are 1 best solutions below

0
On

Whether we can call tests with a running database Unit Test or not, depends on the use case if you need to test against a real database or not.

To generalize it: if the queries are so complex that you can say they are part of the implementation details, then run a database, otherwise just mock the database.

Take a look at this repo to see how you can leverage Docker to instantiate a temporary database for the tests.