I have a function in Go that I want to unit test but that function
contains os.Hostname().Hence i thought of mocking os.Hostname.

Example:

func F(){
hostname, _ := os.Hostname()
}

I tried something like this:

var osHostname = os.Hostname

func TestF(t *testing.T) {
expected := "testing"
defer func() { osHostname = os.Hostname }()
osHostname = func()(string, error) { return "testing", nil }
actual := F()
assert.Equal(t,expected,actual)
}

But this doesn't work.Can someone please point me in the right direction?

Thanks,
Nitish

On Thu, Aug 1, 2019 at 8:18 PM Shulhan <m.shul...@gmail.com> wrote:

> On Thu, 1 Aug 2019 05:09:54 -0700 (PDT)
> Nitish Saboo <nitish.sabo...@gmail.com> 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 ?
> >
>
> I usually does something like these,
>
>   var getHostname = os.Hostname
>
> and in test file,
>
>   getHostname = func() {
>         return "something", nil // or a variable
>   }
>
> --
> { "github":"github.com/shuLhan", "site":"kilabit.info" }
>

-- 
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/CALjMrq7gH4m%2BzExvkuOWyGfyrtRsOp7v-gk20CpkCPQsABY5og%40mail.gmail.com.

Reply via email to