【问题标题】:Mock Method2 of Interface called in another method1在另一个方法1中调用的接口的模拟方法2
【发布时间】:2022-01-18 09:07:44
【问题描述】:

我正在为 Method1() 编写单元测试

我想模拟从同一接口的Method1() 调用的Method2()

我们可以通过在结构中采用模拟实现来轻松模拟另一个接口的方法。但是我不确定如何模拟相同接口的方法。

type ISample interface {
    Method1()
    Method2()
}

type Sample struct {
    
}

func (s Sample) Method1() {
    s.Method2()
}

func (s Sample) Method2() {
    
}

【问题讨论】:

    标签: unit-testing go testing mocking testify


    【解决方案1】:

    可以使用嵌入式接口解决。

    type ISample interface {
        Method1()
        Method2()
    }
    
    type Sample struct {
        ISample
    }
    
    func (s Sample) Method1() {
        s.ISample.Method2()
    }
    
    func (s Sample) Method2() {
        
    }
    

    在创建 Sample 对象时,将模拟的 ISample 分配给 ISample

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多