开发者

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

开发者 https://www.devze.com 2022-12-17 08:30 出处:网络
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 situatio

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.


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


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号