i am trying to write some integration tests for me RESTAPI. I am at the point where i need some testdata. I thought it would be cool to use my Type: User in my Tests from my own package.
type User struct {
ID string `db:"id" json:"id"`
AccountID string `db:"account_id" json:"account_id,omitempty"`
Email string `db:"email" json:"email"`
Password string `db:"password" json:"password,omitempty"`
}
I have defined a new field called valid in the fixtures/users.json.
[
{
"AccountID": "19b849bd-f3db-4a92-8968-603e5473a9e2",
"Email": "mail@domain.tld",
"Password": "test116",
"valid": false
},
{
"AccountID": "19b849bd-f3db-4a92-8968-603e5473a9e2",
"Email": "mail1@domain.tld",
"Password": "test147",
"valid": false
},
{
"AccountID": "403fd0d1-cca1-4a7b-80fb-1a51c85fbde0",
"Email": "mail2@domain.tld",
"Password": "test2617",
"valid": true
}
]
now i have this little helper method to load the json into a my struct.
func loadJSONtoStruct(target interface{}, filename string) error {
file, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Printf("Cant read file: %v
", err)
return err
}
err = json.Unmarshal(file, &target)
if err != nil {
fmt.Printf("Cant unmarshal: %v
", err)
return err
}
return nil
}
package main_test
import (
"encoding/json"
"fmt"
"io/ioutil"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/parnurzeal/gorequest"
"domain.tld/project/backend/package_with-types"
)
type user struct {
package_with-types.User
valid bool
}
var _ = BeforeSuite(func() {
request = gorequest.New()
err := loadJSONtoStruct(&users, "fixtures/users.json")
if err != nil {
fmt.Printf("%+v", err)
}
fmt.Printf("%+v
", users)
})
but i get this nested struct back
[{
User: {
ID: AccountID:
Email:mail@domain.tld
Password:test116
}
valid:false
},
{
User: {
ID: AccountID:
Email:mail1@domain.tld
Password:test147
}
valid:false
},
{
User: {
ID: AccountID:
Email:mail2@domain.tld
Password:test2617
}
valid:false
}]
and i want this:
[{
ID: AccountID:
Email:mail@domain.tld
Password:test116
valid:false
},
{
ID: AccountID:
Email:mail1@domain.tld
Password:test147
valid:false
},
{
ID: AccountID:
Email:mail2@domain.tld
Password:test2617
valid:false
}]
what do you think? should i live with it, and use user.user.ID, user.valid ... in my tests? any hints are welcome i am learning.
thank you Tim
Update
The valid field in my fixtures/users.json dosnt get parsed into the extended struct.I think that Problem is much bigger.
Update 2
Thanks to gavin, this time it was the unexported field:
type user struct {
package_with-types.User
valid bool `json:"valid"`
}