September 16, 2004

JUnit and Inner Classes Are Best Friends

While Java's inner classes are often mentioned with unit testing as a trick to call protected methods and as a way to test asynchronous (threaded) code, it's surprising that writing unit test classes as inner classes aren't one of those idiomatic, the-thing-to-learn-after-HelloWorld standard coding patterns in Java. Say, you are being a good programmer and you always write a unit test class for every class you write. More than once, I've encounter Java programmers mulling over the problem whether they should put their test classes inside the same package to access protected methods or in a different package to better separate them out from the business code. Instead, if you implement them all as inner classes, you get several benefits for free:
- Your unit test class is always kept with the main class if you decide to refactor it into a different package.
- You can name all your test classes the same way, for example as Tester (so you get a bunch of classes called $Tester), which can then easily be identified be removed from deployment builds.
- Inner classes can access all of the fields and methods of the parent class, including private ones, so you don't need to compromise your code encapsulation and information hiding design to instantiate and populate the class you are testing.
- Since inner classes have the same scope as their parents, there's no need to rewrite import clauses.

Any good arguments why NOT to write unit tests as inner classes?

Posted by thoughts at September 16, 2004 01:20 AM | TrackBack
Comments

Very interesting site, beautiful design, thank.

Posted by: Nelly at January 13, 2006 02:57 AM

Good work, webmaster! Nice site!

Posted by: Neo at January 13, 2006 11:18 PM

Yo have nice site, admin! keep up good work man!

Posted by: Rustie at January 15, 2006 11:34 AM

Hi ! Your site is very interesting. Thank you.

Posted by: Neo at July 8, 2006 01:05 AM
Post a comment









Remember personal info?