I am completely confused by figuring out how I can mock a function without using any additional packages like golang / mock. I’m just trying to learn this, but I can’t find a lot of decent online resources.
Essentially, I followed this wonderful article , which explains how to use the interface to mock things.
So I rewrote the function that I wanted to test. The function simply inserts some data into the data warehouse. My tests for this are fine - I can mock a function directly.
The problem I'm running into is mocking the "http route I'm trying to verify." I use the Gin structure.
My router (simplified) is as follows:
func SetupRouter() *gin.Engine {
r := gin.Default()
r.Use(gin.Logger())
r.Use(gin.Recovery())
v1 := r.Group("v1")
v1.PATCH("operations/:id", controllers.UpdateOperation)
}
What calls the UpdateOperation function:
func UpdateOperation(c *gin.Context) {
id := c.Param("id")
r := m.Response{}
str := m.OperationInfoer{}
err := m.FindAndCompleteOperation(str, id, r.Report)
if err == nil {
c.JSON(200, gin.H{
"message": "Operation completed",
})
}
}
So, I need to make fun of the FindAndCompleteOperation () function.
The main (simplified) functions are as follows:
func (oi OperationInfoer) FindAndCompleteOp(id string, report Report) error {
ctx := context.Background()
q := datastore.NewQuery("Operation").
Filter("Unique_Id =", id).
Limit(1)
var ops []Operation
if ts, err := db.Datastore.GetAll(ctx, q, &ops); err == nil {
{
if len(ops) > 0 {
ops[0].Id = ts[0].ID()
ops[0].Complete = true
_, err := db.Datastore.Put(ctx, key, &o)
if err == nil {
log.Print("OPERATION COMPLETED")
}
}
}
}
err := errors.New("Not found")
return err
}
func FindAndCompleteOperation(ri OperationInfoer, id string, report Report) error {
return ri.FindAndCompleteOp(id, report)
}
type OperationInfoer struct{}
To check the route that updates the operation, I have something like this:
FIt("Return 200, updates operation", func() {
testRouter := SetupRouter()
param := make(url.Values)
param["access_token"] = []string{public_token}
report := m.Report{}
report.Success = true
report.Output = "my output"
jsonStr, _ := json.Marshal(report)
req, _ := http.NewRequest("PATCH", "/v1/operations/123?"+param.Encode(), bytes.NewBuffer(jsonStr))
resp := httptest.NewRecorder()
testRouter.ServeHTTP(resp, req)
Expect(resp.Code).To(Equal(200))
o := FakeResponse{}
json.NewDecoder(resp.Body).Decode(&o)
Expect(o.Message).To(Equal("Operation completed"))
})
Initially, I tried to trick a little and just tried something like this:
m.FindAndCompleteOperation = func(string, m.Report) error {
return nil
}
But this affects all other tests, etc.
I hope someone can just explain that the best way to mock the FindAndCompleteOperation function is so that I can test the routes without relying on data storage, etc.