Tried running you code, it's failing:

--- FAIL: TestF (0.00s)
    test.go:43: got ubuntu, want testing
FAIL


On Fri, Sep 20, 2019 at 4:07 PM Mhd Shulhan <m.shul...@gmail.com> wrote:

>
>
> > On 20 Sep 2019, at 17.21, Nitish Saboo <nitish.sabo...@gmail.com> 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 golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CALjMrq5w%3DXTExfFP0gdRnWDGYc3CJ2WkVH8ccP1rYH7_cKGU6Q%40mail.gmail.com.

Reply via email to