包中的模拟方法

I am looking to mock some methods for unit testing. Unfortunately, the code is not structured really well.

var config = struct { abc *abc }

func Init(arg1) {
    // config.abc = newAbc(arg2, arg3)
}   

func UnitTestThis() { 
    //some code here 

    config.abc.Search(arg4,arg5) 

    //code here 
}

How do I unit test the UnitTestThis function, mocking the results of Search method? I have been trying to create an interface and mock the methods, but been unable to do so.

If the config.abc field is a concrete type (or a pointer to a concrete type), you can't really mock it.

You need some refactoring.

With interface

Best would be to change the type of config.abc to interface type, so in tests you can create your own implementation and assign to it, and you can do whatever you want to in it.

Using a method value on config.abc.Search

Another option is to create a variable of function type to hold the method value of config.abc.Search(), and in tests assign a new value to it, a function literal for example.

This is how it could look like:

var config = struct{ abc *abc }{}

var searchFunc func(arg4Type, arg5Type)

func Init(arg1) {
    config.abc = newAbc(arg2,arg3)
    searchFunc = config.abc.Search
}

func UnitTestThis() {
    //some code here
    searchFunc(arg4, arg5)
    //code here
}

Read more about this here: Is it possible to mock a function imported from a package in golang?