I have the following code for a draft test that I am writing. Within the test function I am creating some json.
I have read about testdata
for storing test files.
However, I was thinking along the lines of implementing something like a struct that I could implement to provide methods to return reusable fragments of json for use in tests, e.g:
- valid Author json
- invalid Author missing id attribute
- invalid data section, missing id attribute
This way I would not have to copy and paste the same json fragment within each test and would also avoid reading json from disk in testdata
folder, thus maintain the speed of running tests.
If I add a package containing such an implementation where should it be located so that go excludes it from final executable / release? I am aware that source files ending in _test.go
are not included. Does go provide something similar like a special test package that contains test helper structs / functions for use within tests?
func TestUnmarshalAuthor(t *testing.T) {
sampleData := []byte(`{
"data": {
"attributes": {
"author": "ted",
"id": "400300"
},
"created_on": "2021-01-09T16:39:44.935Z",
"id": "ad27e265-9605-4b4b-a0e5-3003ea9cc4dc",
"modified_on": "2021-01-09T16:39:44.935Z",
"type": "authors"
},
"links": {
"me": "/api/authors/ad27e265-9605-4b4b-a0e5-3003ea9cc4dc"
}
}`)
log.Println("TestUnmarshalAuthor")
log.Println("Trying to unmarshal the data")
var data MyAPIResponse
err := json.Unmarshal(sampleData, &data)
if err != nil {
log.Println("Error unmarshalling")
}
log.Println(data.Links.Me)
log.Println(data.Data.Attributes)
assert.Equal(t, "authors", data.Data.Type)
}
Update
The accepted answer and this link are considered concise relevant answers to my question.