dsfsdf5646 2017-03-16 16:19
浏览 37
已采纳

如何在Golang中仅模拟特定方法

I am fairly new to golang and I am struggling with a simple task.

I have the following class in golang

type struct A {
}

func (s *A) GetFirst() {
    s.getSecond()
}

func (s *A) getSecond() {
    // do something
}

And I want to write some tests for it however for that I need to override getSecond(). I attempted to do the following in my test files

type Ai interface {
    getSecond()
}

type testA struct {
    A
}

func (s *testA) getSecond() {
     // do nothing
}

func TestA(t *testing.T) {
   a := &A{}
   t := &testA{A: a}
   t.GetFirst()  
}

The idea here is to expose A getSecond() method to an interface and override by using embedding however this does not seem to work. The test still calls the original implementation of getSecond() instead of my mocked one.

One solution would of course be to create a proper interface for A which contains getFirst() and getSecond() and then in the test create a struct implementing both where getFirst() call the original implementation and getSecond() a dummy however I feel this is cumbersome and not the correct way of doing things.

Another possibility would be to assign getSecond() in the real implementation to a variable and override the variable in test but I also feel it is a bit strange to do this just for a simple override.

Am I going all wrong about this? Is there any way simpler way to do this using golang?

  • 写回答

1条回答 默认 最新

  • douxie0824 2017-03-16 16:41
    关注

    You can't really override methods in golang as per this answer. However, as you point out you can have a separate interface for the "getSecond method" and have one implementation in your test cases and one implementation in your actual code.

    type s interface{ 
        getSecond()
    }
    
    type A struct{
        s
    }
    
    type a struct{
    
    }
    
    func (s *A) GetFirst() {
        s.getSecond()
    }
    
    func (s a) getSecond() {
        // do something
    }
    
    //Use a 
    A{a{}}
    

    Then in Test have a different implementation of 'a'

    type struct ta {
    
    }
    func (s ta) getSecond() {
        // do nothing
    }
    
    A{ta{}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答