dimanche 1 mars 2020

How use reflect instance in go

Got a problem when trying ues reflect a instance to mock unit tests in go. Code below

type Credential struct{
client credentialClient
}

// This instance what would be test object.
func NewCredential() *Credential{
var client newCredentialClient(nil)
return &NewCredential(client:client)
}

// Below part code is NewCredential's execute logic.
// and I try to reflect newCredentialClient with different parameters "provide", so that I can do unit 
// tests.
type provider interface{
method() 
}

type credentialClient struct{
provid provider
}

// I want to reflect this instance to test.
type newCredentialClient(provid provider) *credentialClient{
if provid == nil{
provid = &a Sturct to execute real logic{}
}

return &credentialClient(provid: provid)
}

My question is that it seems we can reflect a struct, not a instance in go, correct? Or do your have any good suggestion can let me finish this test with reflection? I got this quetion from a go reflect example.

// Student a a
type Student struct {
    Name string
    Age  int
}

// SetName aa
func (c *Student) SetName(name string) {
    c.Name = name
    fmt.Printf("set name %s\n", c.Name)
}

func main() {
    stud1 := &Student{Name: "Geralt", Age: 22}
    val := reflect.ValueOf(stud1)
    val.MethodByName("String").Call(nil)

    fmt.Println(stud1.Name, stud1.Age)
}




Aucun commentaire:

Enregistrer un commentaire