Unit test for String() method of a struct?

In your packages you have defined structs. Each such struct has a String() function.

Do you create unit tests for those String() functions ? Does it make sense to have them, or do they bring too little value - what do you all think ?

I don’t have a definitive answer, just my 2 cents:

  • The only time I bother testing the String function is if the type I’m defining is essentially a wrapper around Go’s builtin string type. For example, I have a type that holds 2 versions of a string: a case-folded string and the “normal” string. Whenever I put values of this type into a map, I use the case-folded string (retrieved via a CaseFold() function), but the type’s String() function always returns the original string. I’ll have a test to make sure these work correctly.

  • For the other 99% of the types I implement, I do not test the output of String because my code should not expect specific output. For those types, if any tests relied on a specific format of String, then the tests are wrong and must be changed to not rely on specific output.

As Russ and Rob say:

func (Time) String

func (t Time) String() string

String returns the time formatted using the format string

“2006-01-02 15:04:05.999999999 -0700 MST”

The returned string is meant for debugging.

There is no need to test debugging output.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.