Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I refactor unit tests? [closed]

This has been driving me nuts lately...

What is refactoring?

Code refactoring is the process of restructuring existing computer code – changing the factoring – without changing its external behavior.

And how do we make sure we don't break anything during refactoring?

Before refactoring a section of code, a solid set of automatic unit tests is needed. The tests are used to demonstrate that the behavior of the module is correct before the refactoring.

Okay fine. But how do I proceed if I find a code smell in the unit tests themselves? Say, a test method that does too much? How do I make sure I don't break anything while refactoring the unit tests?

Do I need some kind of meta-tests? Is it unit tests all the way down?

Or do unit tests simply not obey the normal rules of refactoring?

like image 527
fredoverflow Avatar asked Jul 15 '15 15:07

fredoverflow


1 Answers

In my experience, there are two reasons to trust tests:

  • Review
  • You've seen it fail

Both of these are activities that happen when a test is written. If you keep tests immutable, you can keep trusting them.

Every time you modify a test, it becomes less trustworthy.

You can somewhat alleviate that problem by repeating the above process: review the changes to the tests, and temporarily change the System Under Test (SUT) so that you can see the tests fail as expected.

When modifying tests, keep the SUT unchanged. Tests and production code keep each other in check, so varying one while keeping the other locked is safest.

like image 156
Mark Seemann Avatar answered Oct 20 '22 14:10

Mark Seemann