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 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度