Swetabh
Swetabh

Reputation: 1815

Adding tests while refactoring in test driven development

Let's say that I am refactoring some classes that have unit tests already written. Let's assume that the test coverage is reasonable in the sense that it covers most use cases.

While refactoring I change some implementations. Move some variables, add/remove a few, abstract out things into some functions etc. The api of the classes and it's function has remained the same though.

Should I be adding tests when I am refactoring these classes? Or should I add a new test for every bit of refactoring? This is what I usually do when I am building up code rather than refactoring.

PS: Apologies if this is really vague.

Upvotes: 4

Views: 329

Answers (2)

Jon Reid
Jon Reid

Reputation: 20980

If your changes are verified by current tests, there's no need to add new ones. Check your code coverage. If there are holes in your new code, that means you made an unverified functional change.

New tests might be valuable if a newly extracted class is moved to another project, where you don't have the original tests.

Upvotes: 2

kayess
kayess

Reputation: 3394

Usually unit tests are work-/design-/use case-specifications of how your refactored System Under Test/Class Under Test (eg.: classes) should really work. So by stating this I would really just go as:

  1. Write the test according to your specification
  2. Refactor the code to adhere to the specification
  3. Check the assertation result of the test

In practice I have came to the conclusion that you don't need to test each and every line of your code just for the sake of high percentage of code coverage, but make sure you always test parts of your code where the behaviour or logic lies.

Upvotes: 2

Related Questions