How to solve this syncing issue in Unit testing golang?

Viewed 36

Here when I'm printing the activity it is printing them in the order they are getting created but at the time of assertion it is picking up activities in random order and also it is picking expected values in random order. The api that I'm calling mastercontroller have some goroutines and could take time maybe that is the reason but not sure.

for i, param := range params {
gin.SetMode(gin.TestMode)
        w := httptest.NewRecorder()
        ctx, _ := gin.CreateTestContext(w)

        ctx.Request = &http.Request{
            URL:    &url.URL{},
            Header: make(http.Header),
        }

        MockJsonPost(ctx, param)

        MasterController(ctx)
        time.Sleep(3 * time.Second)

        fmt.Println("response body", string(w.Body.Bytes()))
        fmt.Println("status", w.Code)
        // var activity *activity.Activity
        activity, err := activityController.GetLastActivity(nil)
        //tx.Raw("select * from activity order by id desc limit 1").Find(&activity)
        if err != nil {
            fmt.Println("No activity found")
        }

        activityJson, err := activity.ToJsonTest()
        if err != nil {
            fmt.Println("error converting in json")
        }

        fmt.Printf("reponse activity %+v", string(activityJson))

        assert.EqualValues(t, string(expected[i]), string(activityJson))
}
func MockJsonPost(c *gin.Context, content interface{}) {
    c.Request.Method = "POST" // or PUT
    c.Request.Header.Set("Content-Type", "application/json")

    jsonbytes, err := json.Marshal(content)
    if err != nil {
        panic(err)
    }

    // the request body must be an io.ReadCloser
    // the bytes buffer though doesn't implement io.Closer,
    // so you wrap it in a no-op closer
    c.Request.Body = io.NopCloser(bytes.NewBuffer(jsonbytes))
}
0 Answers
Related