views:

87

answers:

5

Lets says I'm replacing an over complicated method with a much simpler implementation that I believe does the same thing.

Would it make sense for me to copy the old code into a class with my unit tests so I can assert the result of both is the same?

Thanks

+5  A: 

Yes. It's a fine way to get started.

But don't stop there.

Also write a test that has the "final answer" that the old code used to produce.

At some point you will want to delete the old code from your unit tests because it's wrong and unmaintainable.

S.Lott
Ya it doesn't make sense to leave some old big method in your tests crufting up the code
Ryu
Worse, of course, is when you have to do maintenance and revise the unit test output to match the new requirements. The whole point of the rewrite was to get rid of the old software. No encase it in TestCase.
S.Lott
A: 

You could also make your test assert both methods return the same value. Something like

Assert.equals(oldMethod(someInput), newMethod(someInput));

Then you could slowly "set yourself free" from the old method.

Samuel Carrijo
+4  A: 

Assuming you're using source control, here's what I'd do:

  1. Write the tests for the old code.
  2. Make sure the tests pass.
  3. Check that in to source control.
  4. Now, as a separate change, replace the implementation (ie: add new implementation and delete old implementation) and make sure the tests still pass.

As part of step 1 you may want to write a little "harness" for the old code so you can see what values it spits out if your primary goal is just to preserve the existing behavior. The important thing is that you have tests that pass on the old implementation.

The reason for step 3 is that if you ever discover that you missed an important case you can sync to the change where you submitted the tests against the old code, add the new test, verify that it works, and then resync to head and verify that it still works (fixing the new implementation if necessary).

Laurence Gonsalves
+2  A: 

Definitely not. You should have tests to cover each of the cases, boundary conditions, errors, etc., that the old code handles. If your tests are good, your new code is equivalent when the tests pass.

Being able to confidently refactor and eliminate old code is one of the prime benefits of unit testing.

Tim Sylvester
+2  A: 

it would make sense to

write the tests first

and make sure the old code passes them before rewriting it

then replace the old code with your new code, and make sure it passes the same tests

Steven A. Lowe