Skip to content

Instantly share code, notes, and snippets.

@vedashree29296
Created April 21, 2021 05:23
Show Gist options
  • Save vedashree29296/0c0b6e5e0c714dda77ce3344ec118cbf to your computer and use it in GitHub Desktop.
Save vedashree29296/0c0b6e5e0c714dda77ce3344ec118cbf to your computer and use it in GitHub Desktop.
Test to create a category for go chronicles
package rest
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
db "petstore/internal/petstore/repo/postgres"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCreateCategory(t *testing.T) {
var categoryJSON = `{"categoryname":"some_category"}`
response := db.Category{}
// Setup API testing
e := echo.New()
request := httptest.NewRequest(http.MethodPost, "/category", strings.NewReader(categoryJSON))
request.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
recorder := httptest.NewRecorder()
ctx := e.NewContext(request, recorder)
//Assert Creation
if assert.NoError(t, CreateCategory(ctx)) {
// Check status code = 201
assert.Equal(t, http.StatusCreated, recorder.Code)
// Check if the record is created that is id should not be nil or zero
json.Unmarshal(recorder.Body.Bytes(), &response)
require.NotZero(t, response.ID)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment