tercul-backend/internal/data/sql/author_repository_test.go
google-labs-jules[bot] 1655a02a08 Refactor repository tests to be more DRY and maintainable.
Introduced a new testing strategy for the data access layer to avoid redundant testing of generic repository methods.

- Created a comprehensive test suite for the generic `BaseRepository` using a dedicated `TestEntity`. This suite covers all common CRUD operations, including transactions and error handling, in a single location.
- Added a new, focused test suite for `CategoryRepository` that only tests its repository-specific methods, relying on the base repository tests for generic functionality.
- Refactored the existing `AuthorRepository` test suite to remove redundant CRUD tests, aligning it with the new, cleaner pattern.
- Updated the test utilities to support the new testing strategy.

This change significantly improves the maintainability and efficiency of the test suite and provides a clear, future-proof pattern for testing all repositories.
2025-09-06 13:01:04 +00:00

59 lines
1.5 KiB
Go

package sql_test
import (
"context"
"testing"
"tercul/internal/domain"
"tercul/internal/testutil"
"github.com/stretchr/testify/suite"
)
type AuthorRepositoryTestSuite struct {
testutil.IntegrationTestSuite
}
func (s *AuthorRepositoryTestSuite) SetupSuite() {
s.IntegrationTestSuite.SetupSuite(testutil.DefaultTestConfig())
}
func (s *AuthorRepositoryTestSuite) SetupTest() {
s.DB.Exec("DELETE FROM work_authors")
s.DB.Exec("DELETE FROM authors")
s.DB.Exec("DELETE FROM works")
}
func (s *AuthorRepositoryTestSuite) createAuthor(name string) *domain.Author {
author := &domain.Author{
Name: name,
TranslatableModel: domain.TranslatableModel{
Language: "en",
},
}
err := s.AuthorRepo.Create(context.Background(), author)
s.Require().NoError(err)
return author
}
func (s *AuthorRepositoryTestSuite) TestListByWorkID() {
s.Run("should return all authors for a given work", func() {
// Arrange
work := s.CreateTestWork("Test Work", "en", "Test content")
author1 := s.createAuthor("Author 1")
author2 := s.createAuthor("Author 2")
s.Require().NoError(s.DB.Model(&work).Association("Authors").Append([]*domain.Author{author1, author2}))
// Act
authors, err := s.AuthorRepo.ListByWorkID(context.Background(), work.ID)
// Assert
s.Require().NoError(err)
s.Len(authors, 2)
s.ElementsMatch([]string{"Author 1", "Author 2"}, []string{authors[0].Name, authors[1].Name})
})
}
func TestAuthorRepository(t *testing.T) {
suite.Run(t, new(AuthorRepositoryTestSuite))
}