Do Tests Have to Be Written As Good As The Production Code or better?

Posted on Posted in programming

Without tests, you can’t know how the production code works. When you write a test for the production code, you define how the production code works. Latter you can easily change the production code with refactoring or rewrite. Do test have to be written as good as the production code or better?

Question is tricky, because we didn’t define, how good the production code is written.

Example

You started working on a production code that you wrote a few moths ago. You were using specific method “int sum(int a, int b)” and form it’s signature you made a conclusion, that it should sum two integers. You used that method in your new method. First you created test for the new method that fail and then you created implementation for it. After some time you realized that the the sum method didn’t work as expected. It always returned a value 1. You thought that it had a bug.

Maybe tests were wrong. You looked at the tests. You were trying to understand the test code. You conclude that the tests test only that 1 + 0 = 1 and 0 + 1 = 1.

Implementation for the sum method wasn’t wrong for use cases where it was used. Maybe it wasn’t completed yet and maybe it needn’t to be completed.

You added new test for the sum method and upgraded the implementation for it. Then you finished the new method.

Conclusion

How do you know what the sum method should do? Do you look at documentation or at the method body or do you look at tests?

If you want to understand, how the method works, what do you do? You look at the documentation, if it exists. How you make sure, that it works as you expect?

You test it.

Tests are specification for production code. Production code will change more often than test code. Test code is not so easy to change as production code, because we don’t have tests for test code.

If production code is written badly, you can rewrite and tests will take care for correctness.
If test code is written badly, you have difficulties to understand specifications for production code. If you don’t understand specifications, you have trouble to rewrite test code.

Leave a Reply