JUnit extends the base class and conducts tests in this class

I use JUnit 3 and have a situation where often I have to check the correctness of the creation of an object. My idea was to write the MyTestBase class as shown below, and then move on from this to the specific concrete unit tests.

However, in the example I gave, MyTests does not run 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 mistake. The tests in my base class were not named correctly.

+6
java unit-testing junit junit3
source share
4 answers

You said: "MyTests does not run tests in MyTestBase." I tried this and all tests were called, including those that were in MyTestBase.

+4
source share

Well, you can make an abstract MyTestBase so that it does not 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 that will be needed later.

In fact, if you have these abstract methods, you may find that you do not even need the configuration phase, in the first place - you can call abstract methods in which you need a value, instead of using an instance variable. Obviously, this will depend on the specific situation, but in many cases it can be much cleaner.

+2
source share

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

If you want to have common functionality that does some checks

  • define it in the utility class, in static methods
  • define it in a superclass and call it from each test method
0
source share

I don’t know what exactly you want to do, but usually it’s not a good idea for too general parts in the test, because when the general part fails, you will have a large number of tests that will not even be hard, you probably have just one small bug in your software.

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

0
source share

All Articles