mercredi 8 mai 2019

Is there a way to unit test if a function correctly executes stats and logs in Go?

I'm trying to write a unit test for a function that checks a URL string input and increments some stats using a third party package depending on what that URL string is. Since this function only increments stats and returns, how can this be unit tested?

Right now, I just have a test that basically makes sure the function returns and doesn't segfault. The function returns increments different stats and returns no matter what, so my test will pass for all string inputs.

func handleStats(url string) {
    if url == "" {
        stats.Increment(metricForEmptyStringURL)
        return
    }
    stats.Increment(metricForNonEmptyURL)
    if strings.Contains(url, "${") {
        stats.Increment(metricCorrectlyEncodedURL)
    }
}

This is what I currently have (which is not useful since it'll always pass):

func Test_handleStats(t *testing.T) {
    tests := []struct {
        name string
        url  string
    }{
        {name: "Blank", url: ""},
        {name: "No encoding", url: "http://testurl.com/"},
        {name: "With encoding", url: "http://testurl.com/${ENCODING}"},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            handleStats(tt.url)
        })
    }
}

What is the best way to test something like this?

Aucun commentaire:

Enregistrer un commentaire