将测试数据传递到嵌套结构

我正试图掌握Go中的测试,我遇到了一些绊脚石。


我有以下代码:


package main


import (

    "fmt"

    "testing"

)


type ConformanceChange struct {

    Val   string

    Proxy struct {

        Address string

        Port    string

    }

}


func Item(conformance ConformanceChange) string {

    service := conformance.Proxy.Address

    services := map[string]string{

        "Word": "Now",

    }

    service = services[service]

    fmt.Println("Service: ", service)

    return service

}


func Test_Item(t *testing.T) {

    type args struct {

        conformance ConformanceChange

    }

    tests := []struct {

        name string

        args args

        want string

    }{

        // TODO: Add test cases.

        {name: "empty", args: args{

            conformance: ConformanceChange{},

        }, want: ""},

        {name: "value", args: args{

            conformance: ConformanceChange{Val: "test", Proxy: {Address: "d", Port: "d"}},

        }, want: ""},

    }

    for _, tt := range tests {

        t.Run(tt.name, func(t *testing.T) {

            if got := Item(tt.args.conformance); got != tt.want {

                t.Errorf("getService() = %v, want %v", got, tt.want)

            }

        })

    }

}

我希望能够在运行测试时将数据传递给 。我可以将数据传递给它,它的工作原理。ConformanceChange.Proxy.AddressConformanceChange.Val


有人可以让我知道正确的语法吗?


更新祝福提供的解决方案奏效了。


从这里开始,如果我有以下代码:


package main


import (

    "fmt"

    "testing"

)


type ConformanceChange struct {

    Val   string

    Proxy struct {

        Address string `json:address`

        Port    string `json:port`

    }

}


func Item(conformance ConformanceChange) string {

    service := conformance.Proxy.Address

    services := map[string]string{

        "Word": "Now",

    }

    service = services[service]

    fmt.Println("Service: ", service)

    return service

}


我不想指定测试中的所有字段(因为它可能会变得混乱),我可以只指定一个字段吗?在上面的代码中,它失败了:json:端口Cannot use 'struct { Port string  }(struct { Port string }{Port: "d"})' (type struct {...}) as the type struct {...}


森林海
浏览 124回答 1
1回答

ITMISS

创建结构值时,应指定结构。{name: "value", args: args{    conformance: ConformanceChange{Val: "test", Proxy: struct{Address string; Port string}{Address: "d", Port: "d"}},}, want: ""},为了避免重复,您可以定义一个结构Proxytype Proxy struct {    Address string    Port    string}type ConformanceChange struct {    Val   string    Proxy Proxy}然后在初始化结构值时引用它{name: "value", args: args{    conformance: ConformanceChange{Val: "test", Proxy: Proxy{Address: "d", Port: "d"}},}, want: ""},
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go