> On 20 Sep 2019, at 17.21, Nitish Saboo <[email protected]> wrote:
> 
>  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?

I have two notes about your code.
First, F() should have return values but its not.
Second, F() should use osHostname not os.Hostname.

The following pseudocode should works,

```
var osHostname = os.Hostname

func F() (string, error) {
        return osHostname()
}

func TestF(t *testing.T) {
        orgGetHostname := osHostname
        osHostname = func() (string, error) {
                return "testing", nil
        }

        defer func() {
                osHostname = orgGetHostname
        }()

        exp := "testing"
        got, _ := F()

        if exp != got {
                t.Fatalf("got %s, want %s", got, exp)
        }
}
```

-- 
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 [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/7F40F7C1-6C32-4513-966E-D5C91AAD832C%40gmail.com.

Reply via email to