Skip to content
This repository has been archived by the owner on Dec 20, 2023. It is now read-only.

Mock system packages #10

Open
sustrik opened this issue Feb 8, 2019 · 4 comments
Open

Mock system packages #10

sustrik opened this issue Feb 8, 2019 · 4 comments

Comments

@sustrik
Copy link

sustrik commented Feb 8, 2019

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
Copy link
Owner

jmhodges commented Feb 8, 2019

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 bazel-contrib/rules_go#1944

@jmhodges
Copy link
Owner

jmhodges commented Feb 8, 2019

(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
Copy link
Owner

jmhodges commented Feb 8, 2019

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

@sustrik
Copy link
Author

sustrik commented Feb 9, 2019

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

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants