skip to Main Content

I am very new to Go world. I have some db functions that I need to test.
So first I have a database.go file that connects to a postgres db:

import (
    "fmt"
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
    "os"
)

var DB *gorm.DB
var err error

func Open() error {
    dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable", os.Getenv("HOST"), os.Getenv("USER"),
        os.Getenv("PASSWORD"), os.Getenv("DB"), os.Getenv("PORT"))
    DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})

    if err != nil {
        return err
    }

    return nil
}

Then I have a customers.go file with functions that interact with that db:

import (
    "customers/cmd/database"
    "time"
)

type Customers struct {
    ID           int       
    CustomerName string   
    Active       bool      
    Balance      float32   
    ActiveSince  time.Time
}

func Get(id int) (Customers, error) {
    var customer Customers
    result := database.DB.First(&customer, id)

    if result.Error != nil {
        return Customers{}, result.Error
    } else {
        return customer, nil
    }
}

This is all running in docker, there is customers container and postgres container. Now the question is how do I test my Get(id int) function? I was researching dockertest but that spins up a different db and my Get function uses the one I specified in database.go. So is there a standard Go way to test these functions?

2

Answers


  1. it is a docker net problem but golang:

    1. you can create a docker net, run both container in one net.doc
      or use network --network=host

    2. export postgres container’s port to localhost, and customers container link to localhost,-pxx:xx

    Login or Signup to reply.
  2. there is standard way of unit tesing in go. pl refer testing and testify/assert. Unit tests are typically written in xxx_test.go file next to the code.

    coming to unit testing of db access layer code, one option would be to have a testenv helper and use it on these lines.

    customers_test.go:

    package dbaccess
    
    import "testing"
    
    func TestDbAccessLayer(t *testing.T) {
      testEnv := testUtils.NewTestEnv()
      // testEnv should do the required initialization e.g. 
      // start any mocked services, connection to database, global logger etc.
      if err := testEnv.Start(); err != nil {
        t.Fatal(err)
      }
      // at the end of the test, stop need to reset state
      // e.g. clear any entries created by test in db
      defer testEnv.Stop()
    
      // add test code
      // add required assertion to validate 
    }
    
    

    have a separate docker-compose.yml file and use it with docker compose command to start/stop services like postgresdb.

    go test command may be used to run the tests. refer to the command docs for details.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search