0

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.

0

1 Answer 1

1

You may put test helpers in a separate package, and if only test files refer (import) to it, it won't be included in the non-test executable binary.

There is no convention to it like test files having a _test.go suffix. If a package being built refers to it (be it test or non-test), it will be included. Otherwise it won't.

Also note that you may use a special folder testdata to hold static data files for test, the go tool ignores it. Quoting from Command go: Test packages:

The go tool will ignore a directory named "testdata", making it available to hold ancillary data needed by the tests.

2
  • Thanks @icza your advice is appreciated :) So if my test package is only referred to by tests it will not be included? Correct? Jan 10, 2021 at 15:35
  • @anon_dcs3spp Yes, that's correct.
    – icza
    Jan 10, 2021 at 15:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.