qur / withmock

Automatic Go package mock generation tool
Other
71 stars 9 forks source link

Unable to mock net/http packsge #39

Closed ilovewchao closed 9 years ago

ilovewchao commented 9 years ago

SOURCE: github.com/controllers/apps/http_get.go: package apps

import ( "fmt" "net/http" )

func HttpGet() error { res, err := http.Get("http://www.google.com.hk") if err != nil { return err } fmt.Println(res.Status) return nil }

TEST: github.com/controllers/test/unittest/http_get_test.go: package unittest

import ( "testing" "github.com/controllers/apps" "net/http" //mock "code.google.com/p/gomock/gomock" )

func TestHttpGet(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish()

http.MOCK().SetController(ctrl)

res := &http.Response{}

    http.EXPECT().Get("http://www.google.com.hk").Return(res, nil)

err := apps.HttpGet()

if err != nil {
    t.Errorf("SetServiceCredentials return an error: %s", err)
}

}

ERROR: 200 OK --- FAIL: TestHttpGet-2 (1.01 seconds) controller.go:158: missing call(s) to *http._packageMock.Get(is equal to http://www.google.com.hk) controller.go:165: aborting test due to missing call(s) FAIL exit status 1 FAIL github.com/controllers/controller/test/unittest 1.060s

qur commented 9 years ago

If I copy/paste your code I get the following output (after fixing the package names so it actually compiles):

=== RUN TestHttpGet

--- PASS: TestHttpGet (0.00 seconds)
PASS
ok      apps    0.012s

Did your output actually come from running the code you pasted - because things don't match up. The test code has the function TestHttpGet, but the output complains about TestHttpGet-2, and with those package names the code doesn't compile. Also, that code should not take anything like a second to run. The "200 OK" also shouldn't be there, as there is nothing in your test code that injects a status into the code under test.

Also, you don't specify the command you used ...

ilovewchao commented 9 years ago

Sorry, I forget to mention that I used 'withmock go test' to run my test code.

I moved the http_get_test.go file to the same directory with http_get.go after seeing your comment, and finally got a 'PASS'. Turns out the problem is that the product code file and test code file must be placed in the same directory.

But the original output which complains about TestHttpGet-2 comes from running the code I pasted indeed, only the code are placed in a complex project with many other files or dependencies. So the appearance of TestHttpGet-2 is still a confusion.

In all, thank you for your answer!

qur commented 9 years ago

Yeah, I didn't notice you had the code and test in separate directories. Ideally this should work, but withmock needs to know which code is being tested - and currently, this is assumed to be the package the test code is in. I think it will half-work if you aren't mocking stdlib packages ... but in general it isn't going to work at the moment.