interface vs functions for mocking

96 views
Skip to first unread message

Amarjeet Anand

unread,
May 9, 2020, 3:57:50 AM5/9/20
to golang-nuts
Hi
While writing unit test, what should be the preferred way to mock an external(database, http...) call, function based approach or interface based approach?

I don't understand when to use function way and when to use interface way. Which one is more idiomatic Golang way if I am writing my web server from scratch?

Volker Dobler

unread,
May 11, 2020, 3:09:09 AM5/11/20
to golang-nuts
On Saturday, 9 May 2020 09:57:50 UTC+2, Amarjeet Anand wrote:
While writing unit test, what should be the preferred way to mock an external(database, http...) call, function based approach or interface based approach?

I don't understand when to use function way and when to use interface way. Which one is more idiomatic Golang way if I am writing my web server from scratch?

 
Use whatever fits your need. I doubt there is a generic
answer to this question. If it is clear, explicit, readable 
and understandable then it is "idiomatic" no matter what
technique/pattern you use.

Personally I dislike creating an interface just to allow testing
and prefer global functions: I'm thinking of the test as a
bit "secondary" and if the "real" code has only one
implementation of an interface this feels strange. An interface
signals: "Supply whatever implementation fits your need!"
But if there ever is just one "real" implementation this type
of announcement is not clear, explicit or especially
understandable. (Don't get me wrong, I think writing testable
code is important, but clear, understandable code is more
important.)

V.
Reply all
Reply to author
Forward
0 new messages