10

Code evolves, and as it does, it also decays if not pruned, a bit like a garden in that respect. Pruning mean refactoring to make it fulfill its evolving purpose.

Refactoring is much safer if we have a good unit test coverage. Test-driven development forces us to write the test code first, before the production code. Hence, we can't test the implementation, because there isn't any. This makes it much easier to refactor the production code.

The TDD cycle is something like this: write a test, test fails, write production code until the test succeeds, refactor the code.

But from what I've seen, people refactor the production code, but not the test code. As test code decays, the production code will go stale and then everything goes downhill. Therefore, I think it is necessary to refactor test code.

Here's the problem: How do you ensure that you don't break the test code when you refactor it?

(I've done one approach, https://thecomsci.wordpress.com/2011/12/19/double-dabble/, but I think there might be a better way.)

Apparently there's a book, http://www.amazon.com/dp/0131495054, which I haven't read yet.

There's also a Wiki page about this, http://c2.com/cgi/wiki?RefactoringTestCode, which doesn't have a solution.

16
  • 3
    Why are you refactoring the test code? What is gained by that? I don't think I follow the question at all. Can you explain why it's so important to refactor the test? Code doesn't rot spontaneously. Code rot refers to poorly-planned changes. What poorly-planned changes occur in test code? Can you provide a concrete example?
    – S.Lott
    Dec 19, 2011 at 22:00
  • 1
    I write the test, then I write the production code, then I refactor the code, both test and production. I might also refactor the test code later, when I refactor other test code, in order to reduce repetition for example. Dec 19, 2011 at 22:03
  • 1
    "in order to reduce repetition"? Why? I'm still unclear on why you'd ever touch the test code.
    – S.Lott
    Dec 19, 2011 at 22:08
  • 4
    @S.Lott refactoring your test code might actually be as important as refactoring your production code. It's necessary to keep your tests clean, fast and readable. It goes from refactoring your tests to use a fluent interface so that they'll read more like plain english, to eliminating duplicate code in your tests, to establishing test contexts allowing the sharing of resources between your tests... Dec 20, 2011 at 13:38
  • 2
    @S.Lott Please replace all occurrences of "decay" with "are undergoing a slow decay process" in my previous comment. I was obviously not talking about instant decaying but a more long-term trend, we do agree on that one... Except you seem to consider tests can be perfectly well designed right from the start, while I don't. Which is why they need refactoring IMO. Hence Roger's original question ;) Dec 22, 2011 at 23:01

5 Answers 5

2

Refactoring your tests is a two step process. Simply stated: First you must use your application under test to ensure that the tests pass while refactoring. Then, after your refactored tests are green, you must ensure that they will fail. However to do this properly requires some specific steps.

In order to properly test your refactored tests, you must change the application under test to cause the test to fail. Only that test condition should fail. That way you can ensure that the test is failing properly in addition to passing. You should strive for a single test failure, but that will not be possible in some cases (i.e. not unit tests). However if you are refactoring correctly there will be a single failure in the refactored tests, and the other failures will exist in tests not related to the current refactoring. Understanding your codebase is required to properly identify cascading failures of this type and failures of this type only apply to tests other than unit tests.

2
  • 1
    So: 1. Change production code so that the test goes red. 2. Change it back. 3. Refactor the test code, making sure it still goes green. 4. Change the production code again, in the same way. 5. If the test goes red, the refactor was OK. I hope you don't mind if I change your answer to be more to the point. :-) Jan 5, 2012 at 22:03
  • 1
    I like the idea that only one test should go red when I "break" the production code. Jan 5, 2012 at 22:09
2

I think you should not change your test code.

Why? In TDD, you define a interface for a class. This interface contains methods that are defined with a certain set of functionality.The requirements / design.

First: These requirements do not change while refactoring your production code. Refactoring means: changing/cleaning the code without changing the functionality.
Second: The test checks a certain set of functionality, this set stays the same.

Conclusion: Refactoring test and refactoring your production code are two different things.

Tip:When write your tests, write clean code. Make small tests. Which really test one piece of the functionality.

But "Your design changes because of unforeseen changes to the requirements". This may lead or may not lead to changes in the interface.
When your requirements change, your tests must change. This is not avoidable.
You have to keep in mind that this is a new TDD cycle. First test the new functionality and remove the old functionality tests. Then implement the new design.

To make this work properly, you need clean and small tests. Example:

MethodOne does: changeA and changeB

Don't put this in 1 unit test, but make a test class with 2 unit tests.
Both execute MethodOne, but they check for other results (changeA, changeB).

When the specification of changeA changes, you only need to rewrite 1 unit method.
When MethodOne gets a new specification changeC: Add a unit test.

With the above example your tests will be more agile and easier to change.

Summary:

  • Dont refactor your tests, when refactoring your production code.
  • Write clean and agile tests.

Hopes this helps. Good luck with it.

@disclaimer: I do not want your money if this makes you rich.

3
  • 2
    Great but this misses the point IMO. The question was not about changing the test code as a result of changing the requirements. It was about refactoring the test code. "Dont refactor your tests, when refactoring your production code." => this principle is implicit in TDD. You you always re-run the tests between 2 refactoring actions, taking one baby step at a time. Dec 22, 2011 at 8:35
  • I understand your statement. I refer to the fact that you have to write clean test, this way you don't need to refactor the tests. When you think this is not possible, you should follow the principle for testing your methods specification by specification. This way you can create tests that are as small and relevant as possible. Ok and sometimes you have to refactor your tests. There is only one explanation: You are never sure about refactoring unless you have tested the implementation. This translated to the question: you can only achieve this by testing your tests (which is overkill). Dec 22, 2011 at 8:41
  • 1
    @MatsStijlaart I've coached a couple of teams who just started out with unit testing. They don't write there test clean from the start. I've taught them how to use patterns like Builder to clean up there tests,to split tests to test only one thing and other things to make sure that the team doesn't stop writing tests because it's to hard to use them.
    – Wouter de Kort
    Dec 28, 2011 at 15:18
1

How do you ensure that you don't break the test code when you refactor it?

Rerunning the tests should suffice in most cases.

There are some other strategies described here but they might be overkill compared to the few benefits you get.

0
1

Um.

FOR JAVA SOLUTION! I don't know what language you're programming in!

Ok, I just read "Clean Code" by one of the Martins, a book which argues that the idea of refactoring test code to keep clean and readible is fine idea, nad indeed a goal. So the ambition to refactor and keep code clean is Good, not a silly idea like I first thought.

But that's not what you asked, so let's take a shot at answering!

I'd keep a db of your tests - or the last test result, anyway. With a bit of java annotating, you can do something like this:

@SuperTestingFramerworkCapable
public class MyFancyTest {

   @TestEntry
   @Test
   public testXEqualsYAfterConstructors(){
      @TestElement
      //create my object X

      @TestElement
      //create my object Y

      @TheTest
      AssertTrue(X.equals(Y));
   }
}

ANYWAY, you'd also need a reflection and annotation-processing super class, that would inspect this code. It could just be an extra step in your processing - write tests, pass through this super processor, and then, if it passes, run the tests. And your super processor is going to use a schema MyFancyTest

And for each member you have in your class, it will use a new table - here the (only) table would be testXEqualsYAfterConstructors And that table would have columns for each item marked with the @TestElement annotation. And it would also have a column for @TheTest I suppose you'd just call the columns TestElement1, TestElement2 etc etc

And THEN, once it had set all this up, it would just save the variable names and the line annotated @TheTest. So the table would be

testXEqualsYAfterConstructors
TestElement1     |  TestElement2     |  TheTest
SomeObjectType X |  SomeObjectType X |  AssertTrue(X.equals(Y));

So, if the super processor goes and finds tables exist, then it can compare what is already there with what is now in the code, and it can raise an alert for each differing entry. And you can create a new user - an Admin - who can get the changes, and can check over them, crucible style, and ok or not them.

And then you can market this solution for this problem, sell you company for 100M and give me 20%

cheers!

Slow day, here's the rational: yuor solution uses a lot of extra overhead, most damagingly, in the actual production code. Your prod code shouldn't be tied to your test code, ever, and it certainly shouldn't have random variable that are test specific in it. The next suggestion I have with the code you put up is that your framework doesn't stop people breaking tests. After all, you can have this:

@Test
public void equalsIfSameObject()
{
    Person expected = createPerson();
    Person actual = expected;

    check(Person.FEATURE_EQUAL_IF_SAME_OBJECT);
    boolean isEqual = actual.equals(expected);

    assertThat(isEqual).isTrue();
}

But if I change the last two lines of code in some "refactoring" of test classes, then your framework is going to report a success, but the test won't do anything. You really need to ensure that an alert is raised and people can look at the "difference".

Then again, you might just want to use svn or perforce and crucible to compare and check this stuff!

Also, seeing as you're keen on a New Idea, you'll want to read about local annotations:http://stackoverflow.com/questions/3285652/how-can-i-create-an-annotation-processor-that-processes-a-local-variable

Um, so you might need to get that guy's - see the last comment in the link above - you might need his custom java compiler too.

@Disclaimer If you create a new company with code that pretty much follows the above, I reserve the right to 20% of the company if and when you're worth more than 30M, at a time of my choosing

2
  • If I'd modify your last example into a test which doesn't test anything, mu framework would indeed complain, because then it wouldn't fail when I double check it by disabling the production code. Dec 25, 2011 at 22:50
  • mmm, ok, modify the last example so it just returns if the production code is active or not.
    – bharal
    Dec 27, 2011 at 0:56
1

About two months before your question was one of my main questions in refactoring. Just let me explain my experience:

  • when you want to refactor a method, you should cover it with unit tests(or any other tests) to be sure you are not breaking something during refactoring(in my case the team knew the code worked well because they had been using it for 6 years, they just needed to improve it, so all of my unit tests passed in first step).So in first step you have some passed unit tests that cover whole scenarios. If some of unit tests fails, firstly you should fix the problem to be sure your method works correctly.

  • after passing all of tests, you have refactored the method and you want to run your test to be sure every thing is right. Any changes in test codes?

  • you should write tests that are independent from internal structure of method. After refactoring, you should just change some small part of code and in the most of the time no changes are required, because refactoring just improves the structure and doesn't change the behavior. If your test code needed to change a lot, you never know if you've broke some things on main code during refactoring or not.

  • and most important thing for me is to remember in every test, one behavior should be considered

I hope I could explain well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.