views:

173

answers:

4

I am using JUnit 3 and have a situation where often I have to test that an object is created correctly. My idea was to write a class MyTestBase as shown below and then extend from that for the situation specific unit tests.

However in the example I've given, MyTests does not run the tests in MyTestBase.

public class MyTestBase extends TestCase {
   protected String foo;
   public void testFooNotNull() {
     assertNotNull(foo);
   }
   public void testFooValue() {
     assertEquals("bar", foo);
   }
}


public class MyTests extends MyTestBase {
  public void setUp() {
    this.foo = "bar";
  }
  public void testSomethingElse() {
    assertTrue(true);
  }
}

What am I doing wrong?

Update Apologies. Stupid error. The tests in my base class weren't named correctly.

A: 

Well, you could make MyTestBase abstract, so that it didn't try to run tests in the base class. A better solution would be to have setUp in the base class and make it call abstract methods (e.g. getFoo()) to initialize the variables it will require later on.

In fact, if you have those abstract methods you may find you don't even need a set-up phase in the first place - you could call the abstract methods where you need the value, instead of using an instance variable. Obviously it will depend on the exact situation, but in many cases this could be a lot cleaner.

Jon Skeet
+3  A: 

You have said "MyTests does not run the tests in MyTestBase.". I tried it and all tests were called including the ones in MyTestBase.

Petar Minchev
did you try it with JUnit 3?
Bozho
Yes, I tried it from Eclipse with JUnit 3. I ran the MyTests class as a JUnit test and all tests passed successfully.
Petar Minchev
nice. then the question is irrelevant :)
Bozho
A: 

What you are trying to do is not the most appropriate way to achieve your goal:

If you want to have common functionality that makes some checks

  • define it in a utility class, in static methods
  • define it in the superclass and call it from each test method
Bozho
A: 

I don't know what exactly you want to do, but usually it is not a very good idea to too much common parts in test, because when the common part fails you will have a large number of tests that fail even tough you probably have just one small bug in your software.

I suggest you to use a Factory or a Builder to create the complex object and then test the Factory (or Builder) for creating the object correctly.

bertolami