douben8492 2019-03-11 15:41
浏览 15
已采纳

Golang接口和模拟

I'm having hard times writing unit tests in Go due to external libraries which don't expose an interface (therefore not mockable) but only pure functions. Even big ones like Google don't, so I'm wondering whether my approach is good enough. Wouldn't be good practice for libraries to provide interfaces instead of packages with only functions in order to let the user mock them?

The solution I came up with until now is wrap these packages with an interface's implementation but that seem like too much work.

I come with an example. My function could look like this

func AnyFunction() error {
    sess := session.Get("blabla")
    // logic in here...
}

where session is an imported package that returns a struct. I can't mock the package session. For this case I'm going to write a SessionInterface with an implementation, which internally calls session.

Ex:

type SessionInterface interface {
    Get(s string) Session
}

type mySessionImpl struct {}
func (me *mySessionImpl) Get(s string) Session {
  return session.Get(s)
}

For my tests now I can mock the SessionInterface and inject that one into my code

  • 写回答

2条回答 默认 最新

  • douwei2966 2019-03-13 02:27
    关注

    You're doing the right thing here, and this was a conscious decision on the part of the language designers.

    The Go philosophy is that your code should "own" those interfaces, not the library. In languages like C# and Java, libraries define their interfaces up front, without really knowing what the consumer actually needs. (Maybe they include too many methods, or too few.) In Go, because the consumer effectively "owns" the interfaces, you're empowered to specify which methods actually need to be present in a minimal interface, and changes in your program requirements mean that you can also change the interface.

    Now in this particular case it might seem strange to create an adapter in front of a function for testability, but consider the alternative: if session.Get() were a method of an interface or struct, instead of a function, it would force all library consumers to instantiate a dummy object in order to call the method. Not everyone is going to fake it out---it's easier for them to say that the consumers who want to (like you) are empowered to write adapters, and those that don't can blissfully ignore them.

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

报告相同问题?

悬赏问题

  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)