#Example Repo for testing GIN GORM PSQL

3 messages · Page 1 of 1 (latest)

acoustic crater
#

Hello, I am new to golang, and after I build my first (rather complex) backend in gin with gorm, I want to write e2e tests or atleast test the endpoints properly, I googled and came across a few posts but never something with an actual solution.

So here the requirements I want for the tests:

  • Test endpoints, doesn't have to be via a fetch, but just the function that the router points to
  • have a memory psql which I can seed with data, preferably before all tests, then create a connection, and run all tests on that one connection
  • Possibly be able to also create extensions to test fulltextsearch etc. on the db.

What I found/tried/failed

  • Failed: sqlMock, it just doesn't do what I want, I guess this is only to check basic sql stuff
  • Found: embedded-postgres, but I couldn't find a proper example on how to use it with GIN/GORM

My main.go file
Here my attempted test file so you can see the top level that I try to test

#

Here the code coz was too much symbols:

func TestMain(t *testing.T) {
    // Database
    mockdb, _, err := sqlmock.New()
    err.handled(...)
    defer mockdb.Close()

    w := httptest.NewRecorder()
    c, _ := gin.CreateTestContext(w)
    postgresDB := postgres.New(postgres.Config{Conn: mockdb})
    testDB, err := gorm.Open(postgresDB, &gorm.Config{})
    err.handled(...)
    
        validate := validator.New()

    // Repositories
    reviewsRepository := repositories.NewReviewsRepositoryImpl(testDB)
    // Services
    reviewsService := services.NewReviewsServiceImpl(reviewsRepository, validate)
    // Controllers
    reviewsController := controllers.NewReviewsController(reviewsService)

    testID := "1"
    sqlmock.NewRows([]string{"id"}).AddRow(1)

    c.Params = []gin.Param{{Key: "id", Value: testID}}
    reviewsController.FindById(c)
    
    t.Log("Status: ", w.Result().Status) // This is 200
    t.Log("Body: ", w.Body.String()) // This is empty
        // I can guarantee that the code works in production!
        // did some go-playground/assert/v2 here but that didnt matter coz of line above
    if w.Code != 200 {
        t.Errorf("Expected status code 200, but got %d", w.Code)
    }
}
rigid mortar
#

You should take a look at the examples for sqlmock. You're not calling mockdb.ExpectQuery