doutuan6158 2017-11-13 00:33
浏览 38

开始-如何模拟需要回调的依赖项?

Suppose I have a dependency that looks like this:

type Dependency interface {
    Retrieve(transform func(row *Row) string) []string
}

And I'm using it in code that I'd like to unit test

// ...
result := dep.Retrieve(func(row *Row) string {
    // ... do stuff
})
// ...

This is a contrived example, but consider it for something like gcloud pubsub, which has a Receive method that calls a user-defined function for each message it pulls.

If I use mockgen to get a mock of Dependency, how do I tell the mock how to behave? I'd want it to call its input function some number of times with some sets of input.

  • 写回答

1条回答 默认 最新

  • dongxu8533486 2017-11-14 02:38
    关注

    Here is some code while trying to understand what you wanted to achieve. I don't use mockgen, but manually, you can do what you want. I totally changed the behavior between the original and the mocked call. Does it answer your questions?

    package main
    
    import (
        "fmt"
    )
    
    var str = [...]string{
        "world",
        "night",
    }
    
    type Dependency interface {
        Get(val string) string
    }
    
    type dependency struct {
        i int
    }
    
    func (d *dependency) Get(fn func(int) string) string {
        d.i++
        d.i = d.i % len(str)
    
        return "hello " + fn(d.i)
    }
    
    func main() {
        d := dependency{}
        myfn := func(idx int) string { return str[idx] }
        fmt.Println(d.Get(myfn))
        fmt.Println(d.Get(myfn))
        fmt.Println(d.Get(myfn))
    
        m := mock{}
        fmt.Println(m.Get(myfn))
    }
    
    type mock struct {
    }
    
    func (m *mock) Get(fn func(int) string) string {
        i := 0
        j := (i + 1) % len(str)
        k := (j + 1) % len(str)
    
        return "mocked " + fn(i) + fn(j) + fn(k)
    }
    

    The play link: https://play.golang.org/p/bb7WrmlIEN

    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个复杂问题的解释说明
  • ¥50 三种调度算法报错 采用的你的方案
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败