Introducing MagicTest

May 28, 2009

If you’ve written enough JUnit 4 tests, then you should be familiar with code that looks like:

public class FooTest {

  private Foo foo;

  @Before
  public void setUp() {
    foo = new Foo();
  }

  @Test
  public void testBar() {
    assertTrue(foo.bar());
  }
}

Now, how often have you wished it were possible to simply go straight to @Test, do not pass setUp(), do not have to new Foo()?

Introducing MagicTest

So I came up with MagicTest, a parameterized base class for JUnit 4 tests that’ll let us do just that. Read the rest of this entry »

Advertisements

The following code is provided for educational/illustrative purposes only.

This is probably just a clever hack. This is not kosher. To all students of the Java language, please do not start using this in your day-to-day code. Let me be the first to admit that I haven’t used this extensively and I wouldn’t recommend using it for production.

Disclaimers aside, I won’t give any more background into Java generics. For those in need of an introduction, Angelika Langer’s Java Generics FAQ explains a lot of things with more clarity and depth than I ever could.

The basic problem is, given a generic class, we would like to determine the type parameter to that class at run-time..

I’ve found myself needing to do this more than once. The simplest example I can contrive is one when we want the Base class to perform run-time type-checking of some input parameter. Read the rest of this entry »