github.com/kyma-project/kyma-environment-broker@v0.0.1/internal/httputil/json_test.go (about)

     1  package httputil_test
     2  
     3  import (
     4  	"net/http"
     5  	"net/http/httptest"
     6  	"testing"
     7  
     8  	"github.com/kyma-project/kyma-environment-broker/internal/httputil"
     9  
    10  	"github.com/stretchr/testify/assert"
    11  	"github.com/stretchr/testify/require"
    12  )
    13  
    14  func TestEncodeSuccess(t *testing.T) {
    15  	// given
    16  	rw := httptest.NewRecorder()
    17  
    18  	// when
    19  	err := httputil.JSONEncode(rw, fixData())
    20  
    21  	// then
    22  	require.NoError(t, err)
    23  	assert.Equal(t, http.StatusOK, rw.Code)
    24  	assert.Equal(t, "application/json", rw.Header().Get("Content-Type"))
    25  	assert.JSONEq(t, `{
    26  		  "field_int": 1,
    27  		  "field_string": "andrzej"
    28  		}`, rw.Body.String())
    29  }
    30  
    31  func TestEncodeWithCodeSuccess(t *testing.T) {
    32  	// given
    33  	rw := httptest.NewRecorder()
    34  
    35  	// when
    36  	err := httputil.JSONEncodeWithCode(rw, fixData(), http.StatusCreated)
    37  
    38  	// then
    39  	require.NoError(t, err)
    40  	assert.Equal(t, http.StatusCreated, rw.Code)
    41  	assert.Equal(t, "application/json", rw.Header().Get("Content-Type"))
    42  	assert.JSONEq(t, `{
    43  		  "field_int": 1,
    44  		  "field_string": "andrzej"
    45  		}`, rw.Body.String())
    46  
    47  }
    48  
    49  type dataToEncode struct {
    50  	FieldInt    int    `json:"field_int"`
    51  	FieldString string `json:"field_string,omitempty"`
    52  }
    53  
    54  func fixData() dataToEncode {
    55  	return dataToEncode{
    56  		FieldInt:    1,
    57  		FieldString: "andrzej",
    58  	}
    59  }