dqpdb82600 2019-05-29 22:34
浏览 46
已采纳

返回接口的测试功能

I'm having difficulty writing test for the case below.

I'm able to write test for "helper" with a mock object that only implements the functions that used by myself.

How do I write test code for the function 'new' using a mock object without mocking functions C(), D()?

It could be that the other package is written poorly that it should not return an Interface but rather the actual struct?

package main

import (
    "fmt"
)

func main() {
    New()
}

func New() {
    new(NewFromEnvironment)
}

type newTopology func()(Interface,error)

// new is non-exposed simply used for testing purpose.
func new(newTopology newTopology) {
  t,_ :=  newTopology()
  helper(t)
}

// I need to call only A and B
type topologyInterface interface {
    A() string
    B() string
}

func helper(topology topologyInterface) {
    s1 := topology.A()
    s2 := topology.B()
    fmt.Println(s1 + "," + s2)
}

// Below are from other package named "topology".
// I have no control to the code below.

type Interface interface {
    A() string
    B() string
    C() string
    D() string
    //... more
}

func NewFromEnvironment() (Interface, error) {
    return P{}, nil
}

type P struct{}

func (p P) A() string {
    return "A"
}

func (p P) B() string {
    return "B"
}

func (p P) C() string {
    return "C"
}

func (p P) D() string {
    return "D"
}

// more...
  • 写回答

1条回答 默认 最新

  • douyong1850 2019-05-30 02:11
    关注

    You can try creating a struct MockP which embeds P. Then MockP inherits all the methods of P, but you can shadow A() and B() with your own mock implementations. Here's an example:

    package main
    
    import (
        "fmt"
    )
    
    type Interface interface {
        A()
        B()
    }
    
    type P struct {
    }
    
    func (p P) A() {
        fmt.Println("A")
    }
    
    
    func (p P) B() {
        fmt.Println("B")
    }
    
    type MockP struct {
        P
    }
    
    // Shadow P's B() method
    func (p MockP) B() {
        fmt.Println("Mock B")
    }
    
    func main() {
        var p Interface = MockP{}
        p.A()
        p.B()
    }
    

    Output:

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

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)