Skip to content

Commit c8d9143

Browse files
Add test for controller
1 parent 75ec68f commit c8d9143

File tree

1 file changed

+103
-0
lines changed

1 file changed

+103
-0
lines changed
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
package controller_test
2+
3+
import (
4+
"encoding/json"
5+
"errors"
6+
"net/http"
7+
"net/http/httptest"
8+
"testing"
9+
10+
"github.com/amitshekhariitbhu/go-backend-clean-architecture/api/controller"
11+
"github.com/amitshekhariitbhu/go-backend-clean-architecture/domain"
12+
"github.com/amitshekhariitbhu/go-backend-clean-architecture/domain/mocks"
13+
"github.com/gin-gonic/gin"
14+
"github.com/stretchr/testify/assert"
15+
"github.com/stretchr/testify/mock"
16+
"go.mongodb.org/mongo-driver/bson/primitive"
17+
)
18+
19+
func setUserID(userID string) gin.HandlerFunc {
20+
return func(c *gin.Context) {
21+
c.Set("x-user-id", userID)
22+
c.Next()
23+
}
24+
}
25+
26+
func TestFetch(t *testing.T) {
27+
28+
t.Run("success", func(t *testing.T) {
29+
mockProfile := &domain.Profile{
30+
Name: "Test Name",
31+
32+
}
33+
34+
userObjectID := primitive.NewObjectID()
35+
userID := userObjectID.Hex()
36+
37+
mockProfileUsecase := new(mocks.ProfileUsecase)
38+
39+
mockProfileUsecase.On("GetProfileByID", mock.Anything, userID).Return(mockProfile, nil)
40+
41+
gin := gin.Default()
42+
43+
rec := httptest.NewRecorder()
44+
45+
pc := &controller.ProfileController{
46+
ProfileUsecase: mockProfileUsecase,
47+
}
48+
49+
gin.Use(setUserID(userID))
50+
gin.GET("/profile", pc.Fetch)
51+
52+
body, err := json.Marshal(mockProfile)
53+
assert.NoError(t, err)
54+
55+
bodyString := string(body)
56+
57+
req := httptest.NewRequest(http.MethodGet, "/profile", nil)
58+
gin.ServeHTTP(rec, req)
59+
60+
assert.Equal(t, http.StatusOK, rec.Code)
61+
62+
assert.Equal(t, bodyString, rec.Body.String())
63+
64+
mockProfileUsecase.AssertExpectations(t)
65+
})
66+
67+
t.Run("error", func(t *testing.T) {
68+
userObjectID := primitive.NewObjectID()
69+
userID := userObjectID.Hex()
70+
71+
mockProfileUsecase := new(mocks.ProfileUsecase)
72+
73+
customErr := errors.New("Unexpected")
74+
75+
mockProfileUsecase.On("GetProfileByID", mock.Anything, userID).Return(nil, customErr)
76+
77+
gin := gin.Default()
78+
79+
rec := httptest.NewRecorder()
80+
81+
pc := &controller.ProfileController{
82+
ProfileUsecase: mockProfileUsecase,
83+
}
84+
85+
gin.Use(setUserID(userID))
86+
gin.GET("/profile", pc.Fetch)
87+
88+
body, err := json.Marshal(domain.ErrorResponse{Message: customErr.Error()})
89+
assert.NoError(t, err)
90+
91+
bodyString := string(body)
92+
93+
req := httptest.NewRequest(http.MethodGet, "/profile", nil)
94+
gin.ServeHTTP(rec, req)
95+
96+
assert.Equal(t, http.StatusInternalServerError, rec.Code)
97+
98+
assert.Equal(t, bodyString, rec.Body.String())
99+
100+
mockProfileUsecase.AssertExpectations(t)
101+
})
102+
103+
}

0 commit comments

Comments
 (0)