-1

I am attempting to make some JUnit test classes for a project. I've been following the following format:

public class ExampleTest extends TestCase {

How would I make a TestCase if the class already extends something? Like if I had:

public class ExampleTest extends ArrayList<Whatever> {

You can't do:

public class ExampleTest extends ArrayList<Whatever> extends TestCase {

?

How am I supposed to extend TestCase if my class already extends something? Thanks.

zProgrammer
  • 727
  • 4
  • 10
  • 22

2 Answers2

3

You seem to be using Junit 3.x. From Junit 4.0, your test case class doesn't need to extend TestCase. It just needs to have methods annotated with @Test, @Before, @After, @BeforeClass, @AfterClass etc., as required. This would allow your test case class to extend some other class.

In our project, we run JUnit tests using Spring test runner and need to associate a couple of annotations with each test case. We address this by defining an abstract test case, associate the annotations with this abstract test case, and make every other test case extend this.

@RunWith(SpringJunit4TestRunner.class)
@ContextConfiguration(location={})
public class AbstractTestCase
{

}


public class ConcreteTestCase extends AbstractTestCase
{
    @Before
    public void setUp()
    {
        // Some set up before each test.
    }

    @Test
    public void test1()
    {
        // Some test
    }

    @Test
    public void test2()
    {
        // Some other test
    }

    @After
    public void tearDown()
    {
        // Some tear down process after each test.
    }

}
Vikdor
  • 23,934
  • 10
  • 61
  • 84
  • Could you give me an example please? I am using Junit 4.0. My professor was using 3.0, which is where I'm getting this format. – zProgrammer Apr 04 '13 at 01:59
  • @Jack Look at his link. there's examples there. – Jazzepi Apr 04 '13 at 02:00
  • For examples and documentation, go to the JUnit website. It does nobody any good to repeat here information that is readily available on the web. The answer already contains the appropriate link. – Jim Garrison Apr 04 '13 at 02:00
0

Your test class should just be a test class, and not something else. There are valid reasons to wish that Java had multiple inheritance, but this isn't one of them. Any abstract base class should itself extend TestCase if you have common test logic you wish to centralize.

If you have another class of (non-static) helpers you wish to use that cannot itself extend TestCase, you should use composition rather than inheritance.

Matthew Read
  • 1,365
  • 1
  • 30
  • 50