Archive for August, 2005

Porting JUnit extensions to TestNG

Phil Zoio wrote

an interesting article
describing his experience porting a JUnit extension (DBUnit)
over to TestNG.

The bottom line:  it’s very easy.

The nice thing about JUnit extensions is that they usually interface with
JUnit in a very simple manner:  by providing their own base class (which
you need to extend) and their own setUp()/tearDown() methods (which you need to
call in your own setUp()/tearDown()).  And this if course
very easy to emulate with TestNG.

With that in mind, using existing JUnit extensions with TestNG is
straightforward, as Phil convincingly demonstrates.

Phil actually went
even further and leveraged the finer TestNG @Configuration methods to provide a
TestNG extension that’s even more flexible than its JUnit counterpart.

Convenient refactorings in Eclipse

There is a class of refactorings that I am using very often in Eclipse and
since I recently learned a bit more about it, I thought I would share with the
rest of the community.

The refactorings are Extract Method (Alt-Shift-m) and Extract Local Variable

Their use is fairly straightforward, but I discovered by accident recently
that Eclipse is actually more clever than I thought:  when the code segment
you are trying to replace with a method is found at several locations within
your class, the refactoring is automatically applied to all of them.

Here is an example where the three highlighted lines are also repeated in the
method above:

Before After

you can do the same by introducing a local variable to capture an expression
repeated several times:


Before After

Finally, as a curiosity, notice that you can do the opposite as well: 
remove a local variable and replace it with the expression it was assigned to:

Before After

Admittedly, this refactoring is fairly rare but I have used it a few times
already for J2ME programming, where every byte counts.  If you see a local
variable that is only being used once in your code, you should probably consider inlining it.

These refactorings in themselves are pretty benign until you learn their
keyboard shortcuts:

  • Alt-Shift-m for "Extract Method"
  • Alt-Shift-l for "Extract Local Variable"
  • Alt-Shift-i for "Inline Local Variable"

Memorize these shortcuts and very soon, you will be using them everywhere.

Can Eclipse do that?

Okay, I give up.  Until today, I didn’t think there was any question I
couldn’t answer with Google (and for the problem at hand, with the Eclipse help
or the various forums), but all my attempts have completely failed so far, so
I’m hoping asking the question on my blog will work.

In Eclipse, Ctrl-. (control-dot) will take you to the "Next
Problem".  The problem I have with this behavior is that it also stops at
warnings, and most of the time, this is not what I want (I actually filter the
Problems view not to display warnings, so it would make sense for Eclipse to
recognize I have no desire to navigate to these warnings either).

Does anyone know a way to change the "Next Problem" to jump to problems only? 
Or better:  to jump to whatever next item is listed in my Problems window,
which is probably the most flexible way of providing this functionality…

If I get an answer in the comments, my next blog entry will give a few
Eclipse tips.

And if I don’t get any answer…  well, I’ll post the tips anyway but I
will be very disappointed in you all.

Update:  Eugene gave me
, shortly followed by Rane Prashant and then Robert.  Thanks a
lot, guys, you rock!  And I learned something in the process!  Eugene,
my next Eclipse tips are dedicated for you (even though you probably already
know them).


Java Component Object Model

In a previous entry,
I discussed how using mix-ins lets you compose your code to a finer level and
allows you to create smaller bundles of functionalities that you can import and
use on demand.

Of course, it is quite possible to take this practice too far and end up with
code that is not only broken down too much but also spends most of its time
exchanging messages between its various components using more complex
communication ways than it should.  Sometimes, it just makes sense to group
certain methods and fields in the same class.

Formalizing the communication between units of code is a subject that has
received very little exposure until recently, and when you are trying to pass
information between different classes (A to B) or different packages, you
typically use one of the following techniques:

  • Have A create an instance of B with the right parameters and invoke a
    method on it.
  • Have A create an empty instance of B, call a few setters then invoke a
    method on it.
  • A receives an instance of B that has been created somewhere else and
    invokes a method on it.

The hard coupling of A and B is a topic that has already been covered many
times and can be improved by either using interfaces or dependency injection. 
However, there is a third way to accomplish this that I am hoping will be used
more and more:  use a plug-in architecture.

I have written quite a few Eclipse plug-ins these past years (and more
recently, RCP applications) and I started noticing two very interesting trends
in the code that this environment made me produce:

  1. Resuming development on a plug-in I hadn’t worked on for a while was
    very easy, because the various parts of the plug-ins were so clearly
    isolated from each other that I only needed to brush up on a very small
    portion of my code to be able to modify it.
  2. Adding features to an existing plug-in didn’t require understanding the
    existing code base:  all you need to do is read some documentation about the
    area that your plug-in will depend on and focus on that part only.

 In case you were wondering about the reasons behind the explosion of Eclipse plug-ins, look no
further:  the reasons are outlined above, and the bottom line is that the
learning curve to add to existing code with the Eclipse model is extremely small
(and can actually go down over time).  When new developers join your
project, they don’t need to learn a new architecture because that architecture
has been formalized by Eclipse and everybody now agrees on how the plug-ins are
declared and how they interact with each other.  The rest is, literally,
implementation details.

The net result of this new paradigm is that all Eclipse plug-ins and RCP
applications are nothing more than a set of isolated modules that gravitate
around the Eclipse core. 

Another interesting thing about this architecture is that even the
communication between these plug-ins is formalized.  Not only does the
plug-in model offer all the benefits of dependency injection, it also formalizes
how you can receive notifications from other plug-ins, how you can emit
notifications yourself and more importantly, hides all the details pertaining to
upgrades, classloading, and, of course, provides an impressive set of
functionalities that cover everything you will ever need for a client-side
application, including integration with the host operating system (Windows,
MacOS and GTK/Gnome).

Thanks to Eclipse and the RCP, Java is finally on its way toward having a
true component model.  Still not as powerful as COM (only in-process mode
is supported), but definitely one step closer.


Quick Fix for JUnit

The TestNG IDEA plug-in has an interesting feature that I just implemented in
the Eclipse plug-in:  if you press Ctrl-1 (Quick Fix) on a JUnit test
class, the plug-in will give you the option to convert it to TestNG, either with
JDK5 annotations:

or JavaDoc annotations:

The operations performed by this extension are very simple:

  • Remove all the JUnit imports
  • Add TestNG imports (for JDK5 annotations only)
  • Import AssertJUnit
  • Remove extends TestCase
  • Add @Test annotations on top of any method that starts with
  • Add @Configuration(beforeTestMethod = true) on top of setUp()
  • Add @Configuration(afterestMethod = true) on top of
  • Add @Factory on top of suite()

And that’s it!  These are fairly simple changes and again, I am struck
at how intuitive the Eclipse API is.  Manipulating the AST is a real
pleasure and as you can see above, the ASTRewriter gives you a lot of
goodies for free, among which unlimited undo and a nice preview window.


Quantum Software Design

Guido von Rossum is considering adding interfaces to Python.  In this article, he explains that the power of interfaces has forced a few major Python projects to implement their own version of interfaces, which is probably a sign that such a feature is needed in Python itself.

Mix-ins are strikingly absent from Guido’s discussion and I really wonder why.  Mix-ins don’t exactly address the same need as interfaces but they are a better fit for scripting languages where concrete and granular software contracts are more important then schemas.

I actually happen to think that mix-ins would be a very welcome addition to Java as well and I can think of many times when I have needed the functionality provided by a set of methods and I was forced to use one of the following three workarounds:

  • Move these methods in a separate class and make them static.
  • Extend the class they belong to (an approach that is wrong on many counts).
  • Use delegation.

Here is a concrete example of this problem.

Imagine that some of your classes need to expose the properties "shortName" and "longName" with getters and setters.  While interfaces let you specify this contract easily (an interface with four methods), you still need to find a way to capture this implementation in a separate class.

Let’s start with the obvious:

public class Nameable {
  private String m_shortName;
  private String m_longName;

  public String getShortName() {
    return m_shortName;

  public void setShortName(String s) {
    m_shortName = s;

  public String getLongName() {
    return m_longName;

  public void setLongName(String s) {
    m_longName = s;

At this point, Java forces you to use one of the three techniques described above, but imagine we could do the following:

public class Employee {
  import com.beust.Nameable;  // illegal Java
  // ...

Importing the class inside your own class is equivalent to doing a copy/paste of the content of the imported class, so that the following becomes valid:

Employee e = new Employee();
e.setLongName("Cedric Beust");

There are a lot of things to like about this approach:

  • Your Employee class is much less verbose.  Getters and setters are notoriously verbose in Java and while the Ruby equivalent of Nameable would fit on one line, reading through the Java code adds a lot of noise around what should be a simple concept.
  • You are not perverting your type system by extending a class you have no clear "is-a" relationship with.
  • Changes to the imported class are automatically imported into your class, so you don’t need to keep up with them (as you would with delegation since need to implement new forwarding methods if new methods are added to the delegate).

One might argue that the methods imported are not obvious in your class, but this is no different from regular inheritance, and IDE’s can show the imported methods just as easily.

Once the concept of mix-ins is made available to you, you start looking at your code in very different ways and just when you thought you had done a pretty good job at creating small modular classes that interact nicely with each other and isolate the responsibilities in clear ways, you start realizing that you could decompose your architecture much further.  Interfaces allowed you to create a nice abstract schema of your code and mix-ins give you the power to create a nice concrete decomposition as well.  It’s code reuse at its best.

If you take this concept far enough, you end up with "Quantum Software Design", software that is made of a lot of very tiny pieces that you can mix and match at your leisure without compromising your architecture.

I already used the term "Quantum AOP" a couple of years ago to describe software made of tiny aspects that get woven together to create the final product.  This is a very similar concept except that instead of using AOP as the glue, we use a simple, albeit hypothetical as of today, feature of the Java language:  internal class imports.

Interestingly, Quantum Software Design is also a technique that I started identifying recently in my Java code, but this time tied to a totally different framework.  I’ll keep the name of this framework secret for now so I can dedicate an entire entry to it very soon.

Announcing TestNG 2.5

The TestNG team is happy to announce the release of TestNG 2.5.

Highlights of this release:

  • A brand new Web site.
  • An IDEA plug-in, courtesy of Hani Suleiman and
    Mark Derricutt.
  • An improved Maven plug-in.
  • You can now specify entire packages in testng.xml instead of
    enumerating all your test classes.
  • alwaysRun configuration methods:  if a test fails, any
    configuration methods annotated with this boolean will always be run,
    regardless of whether something wrong happened during the tests.
  • Package support in testng.xml.

The full list of changes is included below.

The Eclipse plug-in has also been updated (2.5.0) and is available from the
update site ( or downloadable as a zip file from

Thanks a lot to everyone who contributed to this release, it’s a pretty major
step for TestNG!

Change list for TestNG


  • Added: ITestListener.onTestStart(ITestResult)
  • Added: Support for <packages>
  • Fixed: @Configuration methods were not invoked with individual test methods
  • Added: Resource files for easier ant taskdefs
  • Fixed: Bug with ExpectedExceptions
  • Fixed: Didn’t support nested factory classes
  • Fixed: NPE if -target is omitted with JDK 1.4
  • Fixed: @Configuration failures in a class would cause other classes to fail
  • Fixed: beforeTestClass/afterTestClass were broken for a pathological case
  • Added: @Configuration(alwaysRun)
  • Added: JUnitConverter task
  • Fixed: < and > characters in reports were not escaped

Eclipse plug-in:

  • Fixed: Class dialog wasn’t showing @Factory classes

IDEA plug-in:

  • First release!


  • Added: Brand new look!!!
  • Added: Section on testng.xml
  • Fixed: Numbering of sections


TestNG in Ruby

We’re going global with this baby…

A discussion recently started on the comp.lang.ruby mailing-list about the
possibility to

port TestNG to Ruby

While Ruby doesn’t support annotations natively, it’s actually quite easy to
simulate and both Aslak and a participant
of this thread have posted a technique to add annotations to Ruby.  For

config :after_test => true
def teardown
  puts "Test2#teardown called"

test :groups => [‘one’]
def test_method1
  puts "Test2#test_method1 called"

This trick relies on the fact that it’s possible to add definitions to
in Ruby.  The annotations config and test
above are actually real methods that update fields added to the Class
class.  When one of these methods is encountered in a Class
definition, it is parsed and then silently discarded so it never actually gets
added to the Class definition.  This is made possible by
overriding the method_added method of the Class class, where
you can control what to do whenever a new method definition is found by the

You can find the full listing for an example implementation of this technique

this message from Ryan Leavengood

I also suggested to replace testng.xml with a Ruby file containing
these definitions (the Ruby community is usually not very friendly to XML file,
and I can certainly sympathize with this feeling).

I’m curious to see where all this will lead…


Learning to like early aborts

I am a big fan of single return point functions.  Instead of:

public int dilbert() {
  if (…) {
    return 1;
  else {
    return 0;

I prefer:

public int dilbert() {
  int result = 0;
  if (…) {
    result = 1;
  return result;

There are several advantages to this approach:

  • Clearer flow of execution.  You know the final return result will be run, no matter what.
  • Easier to debug.  I can set a breakpoint on the return and inspect the returned value.

However, I started questioning this habit in a particular case:  when the failure in a condition should cause the method to abort right away.  Compare:

public void dogbert1(Boss b) {
  if (b != null) {


public void dogbert2(Boss b) {
  if (b == null) return;

Until recently, I used to favor the first form because, again, it made the execution flow more obvious.  If you make the second method more complicated and you start peppering returns a bit everywhere, it can become quite difficult to read.

The problem is that dogbert1() can also be difficult to read because "it leaves you dangling".

When you read the first if in dogbert1(), you make a mental note that there might be an else case further down and you will keep it in the back of your mind as you read the body of the if.  When you start adding several nested ifs, the mental state you need to store to understand the method is increasing, and if these else clauses are going to be empty, I would argue that the "early abort idiom" is probably a better choice.

Having said that, I believe there is a happy medium between these two conventions, so I would recommend using the early abort idiom only when…  well, it really is about an early abort.  If your abort logic has to end up buried down a few nested levels and that it’s only one of many other possible cases, you might want to refactor your code so that the abort logic will be featured prominently at the top of your method, as shown above.

What do you think?  In the code you read on a daily basis, what form is more prevalent?