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

Issue

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?

Solution

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

Answered By – Sam

Answer Checked By – Timothy Miller (GoLangFix Admin)

Leave a Reply

Your email address will not be published.