I am coding unit tests in my Go API with Gin Gonic.
Here is my code.
func getKeys(c *gin.Context) {
var meters []models.Meter
metadataOperation, err := metadata.GetOperation("AC123456")
if err != nil {
sendInternalError(err, c)
return
}
meter, err := metadata.GetMeter("12345")
// Other instructions
// ...
// operation = ...
c.JSON(http.StatusOK, operation)
}
Here is GetOperation method:
func GetOperation(operationID string) (Operation, error) {
var operation Operation
var url = metadataAPIURL + "/v2/operations/" + operationID
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return Operation{}, err
}
req.SetBasicAuth(metadataAPIUser, metadataAPIPassword)
res, err := client.Do(req)
if err != nil {
return Operation{}, err
}
if res.StatusCode != 200 {
return Operation{}, errors.New(res.Status)
}
err = json.NewDecoder(res.Body).Decode(&operation)
if err != nil {
return Operation{}, err
}
return operation, nil
}
Thing is metadata.GetOperation("AC123456")
will make a GET request to an external service.
As I understand unit testing, I can't have any external dependencies.
In my case, test is passing, but it is making a GET request to my production server which is not the wanted result.
If I want to use mocks, I shoud have an interface, and switch between dependency, and mock.
It should be great to test GetOperation
method, but for getKeys
method, it seems unclear to me how should I do it.
How should I deal with this situation ? Can anyone give me an example / tuto about this case.
I already checked several tutos about mocking, but I feel it is not responding my use case.
Aucun commentaire:
Enregistrer un commentaire