2016-11-06 68 views
1

得到這個測試我如何解組reflect.Value在Golang

func (t *DeviceTests) CreatePublicDevice() { 
    registerRegularDevice := tester.TableTest{ 
     Method:  "POST", 
     Path:  "/iot/devices", 
     Status:  http.StatusOK, 
     Name:  "CreatePublicDevice", 
     Description: "register Regular Device has to return 200", 
     Body:  PublicDevice, 
    } 
    resp := registerRegularDevice.DoubleSpin(t.Test) 
    log.Println(resp.(types.Device).ID) 

} 

我想保持這種在一個單獨的包,所以我可以在diferent項目中重用。

func (test TableTest) DoubleSpin(t *testing.T) interface{} { 
    actualBody := test.innnerSpin(t) 
    log.Print(string(actualBody)) 
    thetype := reflect.TypeOf(test.Body) 
    log.Println(thetype) 
    receivedev := reflect.Zero(thetype) 
    err := json.Unmarshal(actualBody, receivedev.Interface()) 
    assert.NoError(t, err) 
    log.Println(receivedev) 
    return receivedev.Interface() 
} 

日誌說:

2016/11/06 16:54:01 {"id":"581f7c49b2c79a543c627474","hostname":"Shriekersolar","alias":"my PublicDevice","channels":8,"owner":"public","location":{}} 
2016/11/06 16:54:01 types.Device 
2016/11/06 16:54:01 {ObjectIdHex("") 0 map[]} 
2016/11/06 16:54:01 ObjectIdHex("") 

,其中設備看起來像:

type Device struct { 
    ID  bson.ObjectId  `json:"id" bson:"_id,omitempty"` 
    Hostname string   `json:"hostname"` 
    Alias string   `json:"alias"` 
    Channels int    `json:"channels"` 
    Owner string   `json:"owner"` 
    Location map[string]string `json:"location"` 
} 
+0

你必須傳遞一個指向解組的錯誤 – JimB

+0

'err:= json.Unmarshal(actualBody,&receivedev)'這個工作不能@JimB – CESCO

回答

3

使用reflect.New而不是reflect.Zero獲取一個指針:

thetype := reflect.TypeOf(i) 
receivedev := reflect.New(thetype) 
err := json.Unmarshal(actualBody, receivedev.Interface()) 
if err != nil { 
    panic(err) 
} 

遊樂場:https://play.golang.org/p/pGXRWpBFiF