I've designed my system, so a layer receives an interface for a lower layer. This seems to be the best practice way to create mockable code in golang. The higher level layer can accept any struct that implements the interface, so you can call the higher layer with a real lower layer or a mocked lower layer. The problem is that the lower layers usages are lost. Because of the abstraction, the compiler can't see where the lower layer is used. This visibility is especially important when refactoring, so the programmer can see everywhere a function is used--without relying on control-f. I've included a minimized version of the current architecture, if you were to copy the code into an ide, you could see the issue by attempting to find all usages of Get() > Repository > repository.go
How can I make this pattern work, using interfaces, without shadowing the usages of lower layers?
Package - main
File - main.go
package main
import (
"awesomeProject1/internal"
"fmt"
)
func main() {
realRepo := &internal.Repository{}
realService := internal.Service{Repo: realRepo}
fmt.Println(realService.FindById(1))
}
Package - Internal
File - service.go
package internal
type Service struct {
Repo IRepository
}
type IRepository interface {
Get(id uint64) string
}
func (service *Service) FindById(id uint64) string {
return service.Repo.Get(id)
}
File - repository.go
package internal
type Repository struct {
}
func (repo *Repository) Get(id uint64) string {
return "a real value from db"
}
Package - tests
File - service_test.go
package tests
import (
"awesomeProject1/internal"
"fmt"
"testing"
)
func TestService(t *testing.T) {
mockRepo := &MockRepository{}
realService := internal.Service{Repo: mockRepo}
fmt.Println(realService.FindById(1))
}
File - mock_repository.go
package tests
type MockRepository struct {
}
func (repo *MockRepository) Get(id uint64) string {
return "a fake value for testing"
}