JUnit extend base class and have tests in that class being run

John Oxley picture John Oxley · Jan 26, 2010 · Viewed 22.3k times · Source

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.

Answer

Petar Minchev picture Petar Minchev · Jan 26, 2010

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