This can also be done without an interface: 
https://play.golang.org/p/fgRX2nXIxn0

In ^ example “Thing” would be the type you are working on, with functional 
options 
(https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis 
<https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis>), and 
defaults to using os.Hostname.

PS: Use whichever method works for you, this is just my opinions.

> On Aug 1, 2019, at 6:46 AM, Kyle Butz <kyleb...@gmail.com> wrote:
> 
> You'll want to look into gomock and mockgen.  To get started mocking, you'll 
> need an interface, so maybe writing a receiver function encapsulating 
> os.Hostname(), then consuming that with an interface.
> 
> type OsClient struct {}
> 
> func (o *OsClient) GetOSHostname() (string, error) { return os.Hostname() }
> 
> type HostnameGetter interface { GetOSHostname() (string, error) }
> 
> Gomock repo w/ documentation: https://github.com/golang/mock
> 
> Nice intros to gomock: 
> - https://blog.codecentric.de/en/2017/08/gomock-tutorial/
> - https://www.philosophicalhacker.com/post/getting-started-with-gomock/
> 
> Note to the mods: I accidentally posted this from the wrong, unverified 
> account first
> 
> On Thursday, August 1, 2019 at 7:09:54 AM UTC-5, Nitish Saboo wrote:
> Hi,
> 
> How can we mock a function in Go like os.Hostname() or os.Getwd() ?
> Any framework or Library that we can use for mocking the function calls ?
> 
> Thanks,
> Nitish
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to golang-nuts+unsubscr...@googlegroups.com 
> <mailto:golang-nuts+unsubscr...@googlegroups.com>.
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/golang-nuts/2f288e99-70db-476b-8a4a-75069be9e31a%40googlegroups.com
>  
> <https://groups.google.com/d/msgid/golang-nuts/2f288e99-70db-476b-8a4a-75069be9e31a%40googlegroups.com?utm_medium=email&utm_source=footer>.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/06D9DF57-C818-4A80-AFB2-7A53CB3ECC7B%40interlix.com.

Reply via email to