Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

5
  • 5
    "I would rather compare the value returned by list() instead." - then your test would depend on the correct implementation of list() instead of the correct implementation of toString(). And, not to forget, on the correct implementation of ==. Not much of a difference. Commented Jun 22, 2022 at 21:03
  • Do you have any sensible assertion framework to use instead? If you don't, I'd expect such case to be a workaround for the lack of proper tooling, like GoogleTest matchers. If the alternative is to write EXPECT_THAT(initializeIntegers(), ElementsAre(0, 11)), I'd say that using toString() is a horrible choice. If the alternative is to write a for loop, I'd say it's a good choice to pick a concise option, even if it's semantically inferior. Commented Jun 23, 2022 at 9:56
  • 3
    if your goal is to test for equality, then use the == operator. In your example it is not implemented, but your unit test need already shows that there is a need for this operator. I would add the operator and use that in your test. Implementing the == operator forces you to define when you consider two objects to be the same, which is not necessarily thought about when making a toString() method. Commented Jun 23, 2022 at 14:04
  • Yes, comparing string representations can let some errors squeak through. But it is far better to test that way than not to test at all. And better to have tests that are easy to write, that allow you to re-factor and change your implementation as required, then to have invested a lot of time of code used only for testing, not for the actual application… If that investment then becomes an obstacle to re-factoring and improving your design. If writing the non-string compare tests is fast And easy enough, sure do that from the start. We call it agile for a reason. Commented Jun 24, 2022 at 3:20
  • string(x)=string(y) only implies x=y when string(x)=string(y) implies x=y. That's when string returns a canonical/normal form--by definition of canonical/normal form. Commented Jun 24, 2022 at 22:41