How to Write Unit Test For a Public Function in a Go Module/Library

I am working on a Go Module that is a library for other Go Apps that I have. This module simply gets the required params from the calling Go App and calls an external service and validates/transforms the data and returns an updated struct

// This is the Public Function for the library
func GetNameFromProfile(profileQueryParams ProfileQueryParams) (ProfileResponse, error) {

    customerProfile := &CustomerProfile{
        client: &http.Client{Timeout: 5 * time.Second},
    }
 //This needs to be mocked since we do not want to call the external service during the unit test
    profileResponse, err := customerProfile.getProfile(profileQueryParams)

    if err != nil {
        return profileResponse, err
    }

    // does more transformation/ validation on data and then returns the response. Left out for the sake of brevity

    return profileResponse, nil

}



    func (customerProfile *CustomerProfile) getProfile(profileQueryParams ProfileQueryParams) (CustomerProfileResponse, error) {
        customerProfileResponse := CustomerProfileResponse{}
    
        url := fmt.Sprintf("https://%s.externalservice.com/query", profileQueryParams.customerID)
        req, err := http.NewRequest(http.MethodGet, url, nil)
        // helper method to set headers
        setHeaders(req)
    
        res, err := customerProfile.client.Do(req)
    
        if err != nil {
            return res, fmt.Errorf("network error occurred while calling server. error: %w", err)
        }
    
        defer res.Body.Close()

        customerProfileResponse = someFunctionToReturnJsonResponse(res)
    
        return customerProfileResponse, nil 
    }


type CustomerProfile struct {
    client *http.Client
}

My Question here is how do I Unit Test GetNameFromProfile without changing the signature ie adding dependency injection?

So for getProfile that was fairly simple, Since I have getProfile as a method on CustomerProfile I can simply provide a fake to the client.

Without using dependency injection on GetNameFromProfile I fail to see how I would mock customerProfile.getProfile(), which needs to be mocked so that it does not call the external service during the unit test.

I feel like I am missing something here did I do something incorrect?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.