7

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.

Hilikus
  • 9,954
  • 14
  • 65
  • 118
John Oxley
  • 14,698
  • 18
  • 53
  • 78
  • 1
    Because the system is written in Java 1.4.2 – John Oxley Jan 26 '10 at 08:54
  • I've voted to close the question because it is just wrong. It doesn't ask a real question. – John Oxley Feb 08 '10 at 09:59
  • 1
    @JohnOxley All these years later, I've voted to close as a typo/could not reproduce (because that's what it was). Kinda interesting to see that nearly happened almost a decade ago, too :) – Nic Aug 18 '18 at 00:12

4 Answers4

7

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
  • 46,889
  • 11
  • 103
  • 119
3

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

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
  • 588,226
  • 146
  • 1,060
  • 1,140
0

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
  • 2,896
  • 2
  • 24
  • 41