亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

測試返回接口的函數

測試返回接口的函數

Go
qq_花開花謝_0 2023-06-19 17:14:17
我在為下面的案例編寫測試時遇到了困難。我能夠使用僅實現我自己使用的功能的模擬對象為“助手”編寫測試。如何使用不模擬函數 C()、D() 的模擬對象為函數“new”編寫測試代碼?可能是另一個包寫得不好,它不應該返回一個接口,而是返回實際的結構?package mainimport (    "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 Btype 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 回答

?
holdtom

TA貢獻1805條經驗 獲得超10個贊

您可以嘗試創建一個MockP嵌入P. ThenMockP繼承了 的所有方法P,但您可以使用自己的模擬實現來隱藏A()和。B()這是一個例子:


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()

}

輸出:


A

Mock B


查看完整回答
反對 回復 2023-06-19
  • 1 回答
  • 0 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號