0

How do I mock and add data to a nested JSON struct like the one below please?

type Info struct {
    Accounts []struct {
        AccountUID      string    `json:"accountUid"`
        AccountType     string    `json:"accountType"`
        DefaultCategory string    `json:"defaultCategory"`
        Currency        string    `json:"currency"`
        CreatedAt       time.Time `json:"createdAt"`
        Name            string    `json:"name"`
    } `json:"accounts"`
}

I can unmarshal the data fine coming from the API but would like to create some tests to test the main functions.

  • 2
    If you use anonymous struct type, it's very ugly as you have to repeat the struct definition in the composite literal. Just use named types and so you can reuse the type identifier (without having to repeat the struct definition). – icza Nov 08 '21 at 22:23
  • I test JSON decoding successes and failures within my tests, but don't encode all the data for all the tests. I just instantiate the struct(s) I'm testing, often via helper functions so it's straightforward to enumerate all the different test cases. – erik258 Nov 08 '21 at 23:14
  • 1
    @DanielFarrell I'm not talking about enumerating test cases. I'm talking about using a composite literal to create a value of `Info`. Such a composite literal has to repeat the anonymous struct definition used for the `Info.Accounts` field (if you want to sepcify a non-zero value for that field). – icza Nov 08 '21 at 23:16
  • yeah, your comment is good guidance, I guess maybe it goes without saying you wouldn't have to define all that test data in json – erik258 Nov 08 '21 at 23:36
  • thank you for your comments, this will teach me for using JSON to GO struct haha. Here is a link to a similar problem to mine - https://stackoverflow.com/questions/54125967/how-to-literally-initialize-multi-level-nested-structs-in-go – danny.lyubenov Nov 09 '21 at 09:21

0 Answers0