duanjianxi8439 2014-07-03 23:47
浏览 29
已采纳

Golang网络软件包模拟

I'm trying to learn to write tests in golang on a personal project of mine.

Bunch of the functions in my project are using net package, however since I'm new to this I don't know how to mock the functions from packages such as net one which are interacting with the host's devices.

To make my question more concrete, I have a function similar to this:

func NewThingy(ifcName string) (*Thingy, error) {
    if ifc, err := net.InterfaceByName(ifcName); err == nil {
        return nil, fmt.Errorf("Interface name %s already assigned on the host", ifcName)
    }

    ....

    return &Thingy{
        ifc: ifc,
    }, nil
}

Thingy is clearly defined as:

type Thingy struct {
  ifc *net.Interface
}

Anyone could give me any hints how to go about testing code like this ?

Thanks

  • 写回答

2条回答 默认 最新

  • dongman5539 2014-07-04 01:56
    关注

    Short answer is that you can't mock things like that. Go is a statically compiled language, so unlike ruby or other dynamic languages, there is no support for magically rewriting fixed function calls on the fly.

    If you really want to test it, you have two obvious options:

    • Define NewThingy to take a function pointer whose type matches net.InterfaceByName. Pass that function to all "real" calls to the function, but pass a dummy function pointer in your tests. This will slightly slow down the code however, and isn't pleasant to read or write.

    • Require your test environment to use legitimate data. May or may not be possible depending on your requirements, but there are some packages that may help (I wrote https://github.com/eapache/peroxide for a similar purpose, but it doesn't deal with interfaces so it's probably not what you're looking for).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么