On Thu, Aug 1, 2019, at 12:09, Nitish Saboo wrote: > 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 ?
I don't like to think about "mocking" in Go, but I can't provide an alternative term so maybe this is overly pedantic (or maybe one isn't needed). For something like this, I prefer to avoid global state like others have suggested: eventually, you'll run a test in parallel, try to reuse that state, etc and it will lead to race conditions. You may think you won't now, but it's not a problem until it's a problem so you might as well avoid it. Instead, I'd just pass in a hostname to use. If this isn't something that makes sense in the public API, put it in an internal function and test that: // Foo is a public API that needs a hostname. func Foo() { hostname, err := os.Hostname() // error handling foo(hostname) } // test this func foo(hostname string) { // … } I also prefer to only test published methods using a _testing package, and this flies in the face of that advice a bit but in a situation like this I think it's by far the simplest solution that won't lead to headaches later. —Sam -- 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/4430f2a5-e3ff-497a-a3cd-0f0233778e6c%40www.fastmail.com.