DEV Community

loading...

Discussion on: Unit testing: best practices

Collapse
sandordargo profile image
Sandor Dargo

Thanks for your answer, Elena.

A few months ago, one of our architects commented on my pull request in which I refactored some classes and I was copying the new structure to the tests. He told me that I was basically coupling production and test code and he also shared with me this article about test contra-variance. You might find it interesting.

I think it's always a good practice to start with tests. Unless you are really, I mean really sure that it's just a bit of throw-away code, most probably a prototype.

As I try to follow TDD as much I can, I don't even feel the urge to explain unit testing to the business. It's just the way I write code. Unit tests are part of the code, their cost is part of the estimation. I don't explain to them if statements or polymorphism either, but more the relevant decisions about the business logic we have to make.

Thread Thread
ice_lenor profile image
Elena Author

I have a bit of a different point of view than that article. Let me try to explain.
For me tests are the integral part of the code, just like comments or naming. So I don't really see a problem with changing tests while refactoring.

The most important thing about the code, for me, is how easy it is to read and understand. I do my best to keep the code as plain as possible because I am probably not smart enough to understand and remember complex code. If the tests are not reflecting the code structure at all, like they propose in the article, it becomes very hard for me to understand how tests and code are connected, where they are, and which parts of code they are for.

If I refactor by moving a piece of code to a separate public class or method, I do want a test for it! They propose to only have integration tests for the generic API. But I want to have a unit-test for this new piece too, for several reasons:

  • it is a public API now, can be used in many places independently, so doesn't make sense to only test inside the old code;
  • if we consider tests "documentation" for the code, we need a piece of it for the new code as well;
  • again, I am not smart enough to properly and comprehensively test a complex piece of code which is the generic API. It is easier for me to test in pieces. Modularization and decoupling - also of tests.

Regarding the TDD, I find it an interesting concept, but I never managed to actually start with tests. I don't start with API, I always need some time to crystallize it based on implementation.

Thank you for a very interesting discussion!:)

Thread Thread
sandordargo profile image
Sandor Dargo

I must agree, the most important thing about the code is to make it easy to understand. Then if we understand it, we can correct it, if needed.

Thank you too, it's always interesting to learn about other ways to see the things!

Forem Open with the Forem app