如何在 golang 中创建包含 http 客户端的结构模拟?

how to create a mock of a struct that includes a http client in golang?

我们来看例子:

套餐A:

type Client struct {
    log    bool         
    client *http.Client 
}

type Report struct {
    cli *Client
}

套餐 B:

type H struct {
    r *A.Report
    ............... 
}

现在我想在包 B 中编写一个测试用例,它需要包 A 的模拟报告。包 B 使用包 A 报告进行函数调用。

例如:

H.r.functionA()

本质上,我需要为上面的例子制作一个模拟函数。但是如何为包 B 创建一个模拟报告,以便我可以在包 A 测试文件中使用它?

如果你想写模拟,首先你需要接口。你不能用结构来做到这一点。在上面的示例中,您使用的是结构。以下是从 functionA() 对实现 Report 接口的类型获得模拟响应所需的条件。在包B中,你应该定义一个接口

type Report interface {
    functionA()
}

现在你有了一个接口,你需要改变你的类型 H 来保存这个接口,而不是你在包 A 中定义的结构。

type H struct {
r Report
............... 
}

现在您可以提供接口的模拟实现 Report

type mockReport struct {
}

func (m *mockReport) functionA() {
// mock implementation here
}

在您创建 H 类型的实例时在您的测试文件中,只需为其提供 mockReport 实例

h := H{r: &mockReport{}}
h.r.functionA() // this will call the mocked implementation of your 
                //function