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

Time:03-15

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?

CodePudding user response:

First of all you need interfaces if you want to write mocks. You can not do that with structs. In you4 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
  • Related