如何在Golang中创建一个包含HTTP客户端的结构体的模拟对象?

huangapple go评论80阅读模式
英文:

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的测试文件中使用它呢?

英文:

Let's look at the example:

Package A:

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

type Report struct {
    cli *Client
}

Package B:

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

now I want to write a test case in package B that needs a mock Report from Package A. Package B uses the Package A report to do function calls.

For example:

H.r.functionA()

Essentially, I need to make a mock function for the above example. But how do I create a mock Report for Package B so that I can use it in Package A test files?

答案1

得分: 4

首先,如果你想编写模拟对象,你需要使用接口,而不能使用结构体。在你上面的示例中,你正在使用结构体。下面是你需要做的来从实现了Report接口的类型的functionA()方法中获取模拟响应。在包B中,你应该定义一个接口:

type Report interface {
    functionA()
}

现在你有了一个接口,你需要修改你的类型H,使其持有这个接口,而不是在包A中定义的结构体。

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

现在你可以提供一个接口Report的模拟实现。

type mockReport struct {
}

func (m *mockReport) functionA() {
    // 这里是模拟的实现
}

在你的测试文件中,当你创建H类型的实例时,只需提供mockReport实例即可。

h := H{r: &mockReport{}}
h.r.functionA() // 这将调用你的函数的模拟实现

希望对你有所帮助!

英文:

First of all you need interfaces if you want to write mocks. You can not do that with structs. In your example above you are using structs. Here is what you will need to get a mock response from functionA() on a type that implements the Report interface. In package B, you should define an interface

type Report interface {
    functionA()
}

Now that you have an interface, you would need to change your type H to hold this interface, instead of the struct you have defined in package A.

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

Now you can provide a mocked implementation of the interface Report

type mockReport struct {
}

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

in your test file when you create your instance of type H, just provide it with the mockReport instance

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

huangapple
  • 本文由 发表于 2022年3月14日 22:31:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/71469431.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定