Golang返回指向接口的指针抛出错误

sys*_*cll 7 testing pointers interface mocking go

我在Go中有一个基本功能,它打开一个文件并尝试解码其JSON内容.

我试图提取默认json.NewDecoder()函数,以便我可以在我的测试中轻松模拟它.

但是,我的实现似乎返回一个错误:

不能使用json.NewDecoder(类型func(io.Reader)*json.Decoder)作为NewConfig参数中的类型decoderFactory

码:

package main

import (
    "encoding/json"
    "fmt"
    "io"
    "os"
)

type openFile func(name string) (*os.File, error)

type decoderFactory func(r io.Reader) decoder

type decoder interface {
    Decode(v interface{}) error
}

type Config struct {
    ConsumerKey,
    ConsumerSecret,
    AccessToken,
    AccessTokenSecret string
}

func NewConfig(open openFile, d decoderFactory) (*Config, error) {
    c := new(Config)
    file, err := open("some.file")
    if err != nil {
        return nil, fmt.Errorf("error opening config file")
    }
    defer file.Close()

    decoder := d(file)
    if err := decoder.Decode(&c); err != nil {
        return nil, fmt.Errorf("error decoding config JSON")
    }

    return c, nil
}

func main() {
    _, err := NewConfig(os.Open, json.NewDecoder)
    if err != nil {
        fmt.Fprintf(os.Stderr, "something bad happened: %v\n", err)
    }
}
Run Code Online (Sandbox Code Playgroud)

这是Go游乐场的链接

我哪里错了?

icz*_*cza 5

json.NewDecoder()函数具有以下声明:

func NewDecoder(r io.Reader) *Decoder
Run Code Online (Sandbox Code Playgroud)

它的返回类型是*json.Decoder.json.Decoder不是一个接口,它是一种具体的类型.如果它们的返回类型不同,则有两种函数类型不同:规范:函数类型:

函数类型表示具有相同参数和结果类型的所有函数的集合.

所以你不能构造一个返回接口的新类型,并期望它是相同的json.NewDecoder,或者它将接受该值json.NewDecoder.

"看似"很容易解决的问题是:将你decoderFactory的函数类型定义json.NewDecoder为:

type decoderFactory func(r io.Reader) *json.Decoder
Run Code Online (Sandbox Code Playgroud)

编译,好吧......但现在如何模拟?

现在怎么样?

当然在这种形式下,你将失去模拟的可能性json.NewDecoder()(因为" 嘲弄者"必须返回一个类型的值*json.Decoder而没有别的东西会被接受).该怎么办?

您必须使用不同的工厂类型.工厂类型应该是一个返回接口的函数(您可以提供不同的实现),您在正确的轨道上:

type MyDecoder interface {
    Decode(v interface{}) error
    // List other methods that you need from json.Decoder
}

type decoderFactory func(r io.Reader) MyDecoder
Run Code Online (Sandbox Code Playgroud)

但你不能使用json.NewEncoder as-is作为值传递decoderFactory.但是不要害怕,创建一个decoderFactory可以json.NewEncoder()在引擎盖下调用的类型函数非常容易:

func jsonDecoderFact(r io.Reader) MyDecoder {
    return json.NewDecoder(r)
}
Run Code Online (Sandbox Code Playgroud)

我们嘲笑的是行为json.Decoder,而不是json.NewDecoder()工厂的功能.

使用这个jsonDecoderFact():

_, err := NewConfig(os.Open, jsonDecoderFact)
if err != nil {
    fmt.Fprintf(os.Stderr, "something bad happened: %v\n", err)
}
Run Code Online (Sandbox Code Playgroud)

这是有效的并且编译,因为它jsonDecoderFact具有完全相同的类型decoderFactory.

如果您想使用不同的实现进行测试/模拟:

type TestDecoder struct {
    r io.Reader
}

func (t TestDecoder) Decode(v interface{}) error {
    // Test / mocking logic here
    return nil
}

func testDecoderFact(r io.Reader) MyDecoder {
    return TestDecoder{r}
}
Run Code Online (Sandbox Code Playgroud)

使用它:

_, err2 := NewConfig(os.Open, testDecoderFact)
if err2 != nil {
    fmt.Fprintf(os.Stderr, "something bad happened: %v\n", err2)
}
Run Code Online (Sandbox Code Playgroud)

试试Go Playground上的例子.

  • 我认为鸭子打字可以解决这个问题?由于*json.Decoder实现了解码器 (2认同)
  • @icza-感谢您的详细解释! (2认同)
  • @TimBlackwell duck typing用于匹配方法参数类型的输入,并返回返回类型.但是,它不适用于功能签名.换句话说,如果Foo是具体类型,并且Foo满足Bar,那么F()Foo和F()Bar仍然是两个不同的函数签名.这背后的原因是,如果一个函数返回一个Foo,而你给它一个Bar,那么如果它能够访问该返回值的字段呢?现在它不能,因为它是一个酒吧,甚至可能根本不是一个Foo! (2认同)