How to effectively organize tests for Gin/GORM based web-apps?

38 views Asked by At

I am quite new to web development in Golang using Gin/GORM and I am currently struggling to find out the best practice to organize packages and unit-tests.

The problem arises from the fact I would like all the following requirements to be met:

  • have a dedicated real database for testing
  • place models and controllers respectively in different packages (e.g. models and controllers)
  • have unit-tests in models package for testing correct constraints of each model (NOT NULL, UNIQUE, etc.) using the real database
  • have API integration tests in controllers package using the real database
  • have a single entry point for running database migrations before any tests in models and controllers is run

Useless to say, the blanket has happened to be currently too short for me, at least so far. So, I have currently ended up having two TestMain functions in the two packages which both attempt to migrate the test database. Unfortunately, that is currently source of race conditions as managing concurrency is out of the scope of GORM auto-migrate feature. That means I had to renounce to parallel test execution in order to ensure test goroutines for each package are spawned sequentially.

Another approach I have attempted was to move all tests in a third separate package tests, but that doesn't currently play well with code coverage calculation, as with Go 1.21 coverage is calculated within a single package.

I was also exploring the concept of test suites in testify, but I am skeptical about putting both models and API tests under the same test suite, just to let them share a single setup and teardown routines.

Said that, is there any other battle-tested way to solve this conundrum?

0

There are 0 answers