Home > Mobile >  How to mock go-plugin funcs in golang?
How to mock go-plugin funcs in golang?

Time:11-13

# I want to mock this function
func testCheckPluginFile(fName string){
    plugin, _ := plugin.Open(path.Join("/I/expect/folder/","/plugin-lib-test/" fName))
    plugin.Lookup("symbol")
}

# So I put this func like this
func testCheckPluginFile(fName string,pluginOpen func (path string) (*plugin.Plugin, error)){
    plugin, _ := pluginOpen(path.Join("/I/expect/folder/","/plugin-lib-test/" fName))
    plugin.Lookup("symbol")
}

But I can't do it beacuse of the plugin.Plugin.lookup

Do u have another way to solve it ?

CodePudding user response:

How to mock [...]plugin funcs in go[...]?

You cannot.

If you want to test that you have to use a real plugin.

CodePudding user response:

Mocking in Golang is a bit tricky, and usually requires to generate some code. You need to write interfaces for the plugin package as well as for plugin.Plugin (if the package does not offer these by itself; something which alas is often the case). Then, use a mock generator (the usual suspect being gomock) to create mocks with all the usual mock functionality (expect, conditional return, etc.). In the production code, provide production implementations which you write yourself; they only consist of simple pass-through methods which call the real thing (Open() and Lookup()in this case). (Remember, you want to test whethertestCheckPluginFileworks correctly, not whether theplugin` package works correctly.) By doing so, you should be able to follow proper TDD workflow.

  • Related