Lee
Lee

Reputation: 8734

Golang strategy for testing repository

I have a ClassRepository struct and I would like to test the query ClassesForLastNDays. I am using Gorp to connect to the database, but I cannot work out a nice way of testing my query. Right now it seems that I have to add data to the database, but that is pretty painful as I need to populate unnecessary fields and FKs etc to get my test to work. Perhaps repositories should just not be tested?

package repositories

import (
    "mobifit/app/domain/entities"
)

type ClassRepository struct {
    *Repository
}

func (c *ClassRepository) ClassesForLastNDays(days int) []entities.Class {
    classes := make([]entities.Class, 0)
    query := Select("*").
        From("Class").
        Where("VisibleAt > CURRENT_TIMESTAMP() - INTERVAL ? DAY").
        OrderBy("ClassTypeId").
        Sql()
    c.Repository.Select(classes, query, days)
    c.populateClassRelationships(classes)
    return classes
}

func (c *ClassRepository) populateClassRelationships(classes []entities.Class) {
    for i := range classes {
        class := classes[i]

        // ClassType
        c.Repository.GetById(&class.ClassType, class.ClassTypeId)

        // Instructor
        c.Repository.GetById(&class.Instructor, class.ClassType.InstructorId)

        // Equipment
        query := Select("E.*").
            From("Equipment E").
            Join("ClassEquipment CE on E.Id = CE.EquipmentId").
            Where("CE.ClassId = ?").
            Sql()
        c.Repository.Select(&class.Equipment, query, class.Id)
    }
}

Upvotes: 2

Views: 3874

Answers (1)

alpe1
alpe1

Reputation: 340

Writing an integration test to cover your query code makes perfect sense. It takes more time and effort to seed and access a database but it gives you confidence that your code won't break in production. This safety net will also help you with GORM or database upgrades/migrations in the future.

Integration tests are at the system borders, where you can't do unit testing. They usually run much slower than unit tests, so cover only the required minimum. (Keep the test pyramid in mind)

Fixtures are a good practice to write reusable data seeds. An in memory database may speedup the test runs.

Upvotes: 4

Related Questions