dongsu4345 2019-08-30 09:22
浏览 63

模拟外部库以进行单元测试

I have a below function tryGet() to unit test:

type config struct {
    Key      string        `json:"key"`
    Client   todo.Client  `json:"client"`
}

var instance *config

func (c *config) tryGet() error {
    client := &http.Client{}
    tClient := Client{"http://url", client}
    configValues := config{"Key", tClient} 
    Instance := &configValues
    err := Instance.Client.perform("GET", header)
    return nil
}

// External library in package named "todo" has the below structs and functions

package todo
type Client struct {
    BaseURL         string
    HTTPClient      *http.Client
}

func (client *Client) perform() error {

    return nil
}

I am finding a hard time to mock the Client and perforn in external package todo

  • 写回答

2条回答 默认 最新

  • dongwuzun4630 2019-08-30 09:38
    关注

    You can mock the function as follow

    type myImpl todo.Client 
    
    func (client *myImpl) perform() error {
        // do what you want to assert in the test
        return nil
    }
    

    And then you will use myImpl whenever you have to use todo.Client

    if you are using a function with a parameter of type todo.Client, it will not work if you pass an argument of type myImpl. It will throw an error:

    cannot use client (type myImpl) as type todo.Client in field value

    To solve this issue, an interface can be created

    type Client interface {
        perform() error
    }
    

    Now the type Client should replace the type todo.Client of the function to be unit tested.

    type config struct {
        Url      string        `json:"url"`
        Client   Client        `json:"client"`
    }
    

    With this change the above code which supply an implementation myImpl of the interface Client should work

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化