[unit test] Do you use reflect.DeepEqual(expected, actual) or just compare their string values ?)

In a unit test, for a function that returns a large struct. Do you use deepEqual or just create the string value fmt.Sprintf("%v", actual) and compare that with an expected string ?

I am thinking that in case of a refactoring, if a new field is added to that result struct, the deepEqual test will still work while the test comparing only string values fails, thus signaling that it needs refactoring. Also, if the two objects contain functions, reflect.DeepEqual() will produce false instead of true, while the string approach will still work.

This makes me favor the string approach, what do you think ?

Is there any discussion, or blog article about this, so far I could find none ? What are the pros and cons of these 2 approaches ?

Is it necessary to assert the complete struct to be equal? Is this really what you want to test?

THe most common scenario for my unit tests is: I call method F with some parameters, and it produces a struct. This struct has 5-20 fields. Out of these only 3-4 are interesting, the rest are fluff.

I have a harcoded expected string and assert that my expected is equals to fmt.Sprintf("%v", result).
Now, this is convenient for me as I just store a 1 line string, instead of building the object.

But the alternative si construc an expected object with all its fields completed, and test with DeepEqual. Again, only 3-4 fields are important in the context of that test, the rest are simply there for show.

Any advice ?

I would not test the fluff. Just assert the fields that are of interest and that the tested code may have an effect on.

It is advisable to make the intention of a test clear. Asserting a long string does not tell the reader why the string is epected to be like this. Asserting only the interesting fields is better.

But when I want to compare all fields, lets say I test a “get from the database” method. What then ?

If you want to compare all fields you will have to compare all fields. One by one.

If you want to compare that object a is equal to object b, compare them using the == operator:

Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.

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