Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ===============================domain/user_dao.go
- package domain
- import (
- "fmt"
- "log"
- "github.com/jkrovnl/golearn2/utils"
- )
- var (
- users = map[int64]*User{
- }
- UserDao userDaoInterface
- )
- func init() {
- UserDao = &userDao{}
- }
- type userDaoInterface interface {
- GetUser(int64) (*User, *utils.ApplicationError) //ja int32 tad init nestradas jo nav pareizi parametri
- }
- type userDao struct{}
- func (u *userDao) GetUser(userId int64) (*User, *utils.ApplicationError) {
- log.Println("We are accesing database.")
- if user := users[userId]; user != nil {
- return user, nil
- }
- return nil, &utils.ApplicationError{
- Message: fmt.Sprintf("user %v was not found", userId),
- StatusCode: 404,
- Code: "not_found",
- }
- }
- ===============================services/user_service.go
- package services
- import (
- "github.com/jkrovnl/golearn2/domain"
- "github.com/jkrovnl/golearn2/utils"
- )
- type usersService struct{}
- var UsersService usersService
- func (u *usersService) GetUser(userId int64) (*domain.User, *utils.ApplicationError) {
- return domain.UserDao.GetUser(userId)
- }
- ===============================services/user_service.go
- package services
- import (
- "net/http"
- "testing"
- "github.com/jkrovnl/golearn2/domain"
- "github.com/jkrovnl/golearn2/utils"
- "github.com/stretchr/testify/assert"
- )
- var (
- userDaoMock usersDaoMock
- getUserFunction func(userId int64) (*domain.User, *utils.ApplicationError)
- )
- func init() {
- domain.UserDao = &usersDaoMock{}
- }
- type usersDaoMock struct{}
- func (n *usersDaoMock) GetUser(userId int64) (*domain.User, *utils.ApplicationError) {
- return getUserFunction(userId)
- }
- func TestGetUserNotFoundInDatabase(t *testing.T) {
- getUserFunction = func(userId int64) (*domain.User, *utils.ApplicationError) {
- return nil, &utils.ApplicationError{
- StatusCode: http.StatusNotFound,
- Message: "user 0 was not found",
- }
- }
- user, err := UsersService.GetUser(0)
- assert.Nil(t, user)
- assert.NotNil(t, err)
- assert.EqualValues(t, http.StatusNotFound, err.StatusCode)
- assert.EqualValues(t, "user 0 was not found", err.Message)
- }
- func TestGetUserNoError(t *testing.T) {
- getUserFunction = func(userId int64) (*domain.User, *utils.ApplicationError) {
- return &domain.User{
- Id: 321,
- }, nil
- }
- user, err := UsersService.GetUser(123)
- assert.Nil(t, err)
- assert.NotNil(t, user)
- assert.EqualValues(t, 321, user.Id)
- }
Add Comment
Please, Sign In to add comment