dsgw3315 2018-08-09 06:45
浏览 50
已采纳

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

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 ?

  • 写回答

1条回答 默认 最新

  • dongyuans61046 2018-08-09 07:19
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 数字信号处理实验报告
  • ¥15 ensp路由器启动不了一直报#
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程