Abstract Class Testing using JUnit

This week I had to move some tests around for some concrete classes that extended some abstract classes. If you search on Google "testing abstract classes" it will return an entry in StackOverflow suggesting a mock in order to do that. Well, that's not the best approach and digging a little bit more there's way more suggestions on using Mocks.

Few entries will actually show that you can rely on JUnit to do the right thing, do not go for mocking right away unless you really need. The relationship between a Concrete and Abstract class is too close for you call it "collaboration", where Mocks or Stubs are more suitable.

If you check the JUnit FAQ for "How to test abstract classes?" it points to C2 (http://c2.com/cgi/wiki?AbstractTestCases) If you check it out the information it is a little bit raw, so I decided to blog the work to make more clear how you should test your abstract classes.

Thinking about this post I realized that if I post a step by step guide it will be very long and boring. I decided then to screen record one session where I code two simple classes, extract an abstract class and do the same for the tests.

Inspired by BioJava (http://biojava.org/wiki/Main_Page) framework I'll code a DNA sequence and one RNA sequence class. DNA and RNA are composed by nucleotides represented by the letters A, C, G, T and U, where DNA uses A, C, G and T and RNA uses A, C, G, and U (U instead of a T). For our exercise a sequence can represent itself as a String and can also reverse itself (like "ACGGG" will turn to be "GGGCA"). It's a nice problem and get's out of the common code samples we see around.

The video has aprox 13 minutes and it's speeded up 2x. As you watch the video please pay attention on these:

  • The coverage of the code, once it gets 100% it should stay there no matter the refactoring.
  • The number of tests, it will be 6 total, extracting the tests to the abstract class should not lower this number as JUnit will run each test for each concrete class.
  • Refactorings, usually your IDE can do the heavy lifting for you, I hope you can learn one or two more refactorings watching the video.
Published in Sep 23, 2011