Golang interfaces & mocking

前端 未结 2 1571
谎友^
谎友^ 2021-02-20 16:38

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 G

2条回答
  •  日久生厌
    2021-02-20 17:15

    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.

提交回复
热议问题