0

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?

vpham
  • 9
  • 1
  • 2
    I'm not sure what the "stats" package is, but why can't you just read them after each test step? – JimB May 08 '19 at 19:21
  • 1
    @vpham you can wrap the 3rd party library and return something that you can test with – Miguel Mota May 08 '19 at 19:23
  • Using the "real" stats library, this is an integration test. To unit test this code, you would use a mock/stub instead and use that to ensure the logic is correct. – Adrian May 08 '19 at 19:39

0 Answers0