I have simple learning clean architecture app written in golang
. I wanna add test to my service package. I put the test file under service_test package. When i running my test, it always show error cannot found storage/log. I realize it just the place where i put my logging file to contain all my logging in one place. The test cannot find the file because it run in different root from project root. My question is : Is this the default behavior of golang
test package? Does go test also running main function?
I tried several things to make sure that this is not a result of some side effect. I tried to remove dot import to make sure not to inadvertently running init
function and thus running the file that i dont wannna to include. For some clarification i will include my code. I am just curious not in hurry.
My test File
package service_test
import (
"testing"
"github.com/jurassicia/go-simple-clean-microservice/entity"
"github.com/jurassicia/go-simple-clean-microservice/service"
"github.com/jurassicia/go-simple-clean-microservice/utils"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
type PostRepositoryMock struct {
mock.Mock
}
func (m *PostRepositoryMock) Save(post *entity.Post) (*entity.Post, utils.CustomError) {
args := m.Called(post)
return args.Get(0).(*entity.Post), nil
}
func (m *PostRepositoryMock) FindAll() ([]entity.Post, utils.CustomError) {
args := m.Called()
return args.Get(0).([]entity.Post), nil
}
func TestCreate(t *testing.T) {
postRepository := new(PostRepositoryMock)
postRepository.On("Save", mock.Anything).Return(&entity.Post{}, nil)
postService := service.NewPostService(postRepository)
post := &entity.Post{
Title: "title",
Body: "body",
}
_, err := postService.Create(post)
assert.Nil(t, err)
}
My Tested file
package service
import (
"github.com/jurassicia/go-simple-clean-microservice/entity"
repository "github.com/jurassicia/go-simple-clean-microservice/repository/post_repository"
"github.com/jurassicia/go-simple-clean-microservice/utils"
)
type PostService interface {
Create(post *entity.Post) (*entity.Post, utils.CustomError)
FindAll() ([]entity.Post, utils.CustomError)
}
type service struct{
repo repository.PostRepository
}
func NewPostService(repo repository.PostRepository) PostService {
return &service{
repo: repo,
}
}
func (s *service) Create(post *entity.Post) (*entity.Post, utils.CustomError) {
return s.repo.Save(post)
}
func (s *service) FindAll() ([]entity.Post, utils.CustomError) {
return s.repo.FindAll()
}
My Main Function
package main
import (
"github.com/jurassicia/go-simple-clean-microservice/database"
"github.com/jurassicia/go-simple-clean-microservice/config"
"github.com/jurassicia/go-simple-clean-microservice/router"
)
var (
)
func main() {
database.Migration()
engine := config.Server()
router.InitApiRouter(engine)
config.InfoLog.Println("Server running on port 3540")
engine.SERVE(":3540")
}
and i am doing some init in migration and config log