|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "net/http" |
| 6 | + "net/http/httptest" |
| 7 | + "testing" |
| 8 | + |
| 9 | + mockdb "github.com/belito3/go-web-api/app/repository/mock" |
| 10 | + |
| 11 | + "github.com/belito3/go-web-api/app/config" |
| 12 | + "github.com/belito3/go-web-api/app/repository/impl" |
| 13 | + "github.com/belito3/go-web-api/app/util" |
| 14 | + "github.com/golang/mock/gomock" |
| 15 | + "github.com/stretchr/testify/require" |
| 16 | + "go.uber.org/dig" |
| 17 | +) |
| 18 | + |
| 19 | +func TestGetAccountAPI(t *testing.T) { |
| 20 | + account := randomAccount() |
| 21 | + |
| 22 | + ctrl := gomock.NewController(t) |
| 23 | + defer ctrl.Finish() |
| 24 | + |
| 25 | + store := mockdb.NewMockIStore(ctrl) |
| 26 | + // build stubs |
| 27 | + store.EXPECT(). |
| 28 | + GetAccount(gomock.Any(), gomock.Eq(account.ID)). |
| 29 | + Times(1). |
| 30 | + Return(account, nil) |
| 31 | + |
| 32 | + // Build container |
| 33 | + container := dig.New() |
| 34 | + conf := config.AppConfiguration{} |
| 35 | + //// Inject store to container |
| 36 | + _ = container.Provide(func() impl.IStore { |
| 37 | + return store |
| 38 | + }) |
| 39 | + |
| 40 | + // start test server and send request |
| 41 | + server := NewServer(conf, container) |
| 42 | + // Inject api to container |
| 43 | + _ = server.InitGinEngine() |
| 44 | + |
| 45 | + recorder := httptest.NewRecorder() |
| 46 | + |
| 47 | + url := fmt.Sprintf("/api/v1/account/%d", account.ID) |
| 48 | + request, err := http.NewRequest(http.MethodGet, url, nil) |
| 49 | + require.NoError(t, err) |
| 50 | + |
| 51 | + server.router.ServeHTTP(recorder, request) |
| 52 | + // check response |
| 53 | + require.Equal(t, http.StatusOK, recorder.Code) |
| 54 | +} |
| 55 | + |
| 56 | +func randomAccount() impl.Account { |
| 57 | + return impl.Account{ |
| 58 | + ID: util.RandomInt(1, 1000), |
| 59 | + Owner: util.RandomOwner(), |
| 60 | + Balance: util.RandomMoney(), |
| 61 | + Currency: util.RandomCurrency(), |
| 62 | + } |
| 63 | +} |
0 commit comments