如何在测试案例中模拟结构的方法调用

Here is the sample code for the struct and its method

type A struct {}

func (a *A) perfom(string){
...
...
..
} 

Then i want to call the method from the function invoke() residing outside the package, sample code

var s := A{}
func invoke(url string){
   out := s.perfom(url)
   ...
   ...
} 

I want to write the test case for the function invoke by mocking the perform method of A.

In java, we have mockito, jmock framework to stub method calls.

Is there any way in go, we can mock the method call of the struct without introducing interfaces in source code ?

To mock a method call, you need to make a mock of your structure.

With the code example you provided, I would recommend making a Performer interface that implements your Perform call. Both your real structure and your mock structure would implement this interface.

I would also recommend passing your structure as an argument to the invoke function instead of using a global variable.

Here is an example:

type Performer interface {
    perform()
}

type A struct {
}

func (a *A) perform() {
    fmt.Println("real method")
}

type AMock struct {
}

func (a *AMock) perform () {
    fmt.Println("mocked method")
}

func caller(p Performer) {
    p.perform()
}

In your tests, inject the mock to your invoke call. In your real code, inject the real structure to your invoke call.

Using a library like https://godoc.org/github.com/stretchr/testify/mock you will even be able to really easily verify that your method is called with the right arguments, called the right amount of times, and control the mock's behavior.