jmhodges / bazel_gomock

Code to create Go mocks for bazel targets using mockgen
MIT License
58 stars 30 forks source link

Mock system packages #10

Open sustrik opened 5 years ago

sustrik commented 5 years ago

Is there a way to mock a system package, e.g. net.Addr?

Manually, I would run the following command:

mockgen -destination=addr.go net Addr

In bazel_gomock, however, the source is a bazel target and can't be set to "net".

jmhodges commented 5 years ago

I have a workaround for you and have opened a ticket with the rules_go folks to make a nicer solution.

It looks like there's no bazel targets for individual packages in the stdlib provided by rules_go (in the @go_sdk external or something), so we don't have the easy solution of just plopping that in.

What we can do is use a type alias and use gomock in reflect mode (not source mode because source mode can't import packages).

So, you'd add something like

type Addr = net.Addr

to a source file under your control. Then you'd set it up the reflect mode gomock as something like:

gomock(
    name = "addr_mock",
    out = "addr_test.go",
    interfaces = [
        "Addr",
    ],
    library = ":go_default_library",
    package = "mynetlib", # or whatever
)

The important bits are that the library is set to the bazel target and go package with your type alias in it and that you're not using the source parameter.

You don't have to actually use your local Addr type in all of your functions. The generated mock will work as a net.Addr just fine.

I'm going to leave this open til we figure out if there's a better solution in https://github.com/bazelbuild/rules_go/issues/1944

jmhodges commented 5 years ago

(I'm pretty sure that you don't have to export that type alias, too, if the alias is in the same package as the generated and test code but haven't checked it.)

jmhodges commented 5 years ago

(Typoed the interfaces param values in the original comment, but have corrected it)

sustrik commented 5 years ago

Great, thanks! I'll give it a try on Monday.