Add asserts test util

For comparing the body of a request with an instance.
This commit is contained in:
Jannis Mattheis 2018-03-24 16:39:57 +01:00 committed by Jannis Mattheis
parent 42c5cc15d8
commit d452b8b8ae
2 changed files with 69 additions and 0 deletions

27
test/asserts.go Normal file
View File

@ -0,0 +1,27 @@
package test
import (
"encoding/json"
"io/ioutil"
"net/http/httptest"
"github.com/stretchr/testify/assert"
)
// BodyEquals asserts the content from the response recorder with the encoded json of the provided instance.
func BodyEquals(t assert.TestingT, obj interface{}, recorder *httptest.ResponseRecorder) {
bytes, err := ioutil.ReadAll(recorder.Body)
assert.Nil(t, err)
actual := string(bytes)
JSONEquals(t, obj, actual)
}
// JSONEquals asserts the content of the string with the encoded json of the provided instance.
func JSONEquals(t assert.TestingT, obj interface{}, expected string) {
bytes, err := json.Marshal(obj)
assert.Nil(t, err)
objJSON := string(bytes)
assert.JSONEq(t, expected, objJSON)
}

42
test/asserts_test.go Normal file
View File

@ -0,0 +1,42 @@
package test_test
import (
"net/http/httptest"
"testing"
"github.com/gotify/server/test"
"github.com/stretchr/testify/assert"
)
type obj struct {
Test string
ID int
}
type fakeTesting struct {
hasErrors bool
}
func (t *fakeTesting) Errorf(format string, args ...interface{}) {
t.hasErrors = true
}
func Test_BodyEquals(t *testing.T) {
recorder := httptest.NewRecorder()
recorder.WriteString(`{"ID": 2, "Test": "asd"}`)
fakeTesting := &fakeTesting{}
test.BodyEquals(fakeTesting, &obj{ID: 2, Test: "asd"}, recorder)
assert.False(t, fakeTesting.hasErrors)
}
func Test_BodyEquals_failing(t *testing.T) {
recorder := httptest.NewRecorder()
recorder.WriteString(`{"ID": 3, "Test": "asd"}`)
fakeTesting := &fakeTesting{}
test.BodyEquals(fakeTesting, &obj{ID: 2, Test: "asd"}, recorder)
assert.True(t, fakeTesting.hasErrors)
}