JUnit confusion: use 'extend Testcase' or '@Test' ?

Posted by Rabarberski on Stack Overflow See other posts from Stack Overflow or by Rabarberski
Published on 2010-04-14T08:16:27Z Indexed on 2010/04/14 8:23 UTC
Read the original article Hit count: 309

Filed under:
|
|
|

I've found the proper use (or at least the documentation) of JUnit very confusing. This question serves both as a future reference and as a real question.

If I've understood correctly, there are two main approaches to create and run a JUnit test:

Approach A: create a class that extends TestCase, and start test methods with the word test. When running the class as a JUnit Test (in Eclipse), all methods starting with the word test are automatically run.

import junit.framework.TestCase;
public class DummyTestA extends TestCase {

    public void testSum() {
        int a = 5;
        int b = 10;
        int result = a + b;
        assertEquals(15, result);
    }
}

Approach B: create a 'normal' class and prepend a @Test annotation to the method. Note that you do NOT have to start the method with the word test.

import org.junit.*;
import static org.junit.Assert.*;

public class DummyTestB {

    @Test
    public void Sum() {
        int a = 5;
        int b = 10;
        int result = a + b;
        assertEquals(15, result);
    }
}

Mixing the two seems not to be a good idea, see e.g. this stackoverflow question:

Now, my questions(s):

  1. What is the preferred approach, or when would you use one instead of the other?
  2. Approach B allows for testing for exceptions by extending the @Test annotation like in @Test(expected = ArithmeticException.class). But how do you test for exceptions when using approach A?
  3. When using approach A, you can group a number of test classes in a test suite.
    TestSuite suite = new TestSuite("All tests");<br/> suite.addTestSuite(DummyTestA.class);
    suite.addTestSuite(DummyTestAbis.class);`
    But this can't be used with approach B (since each testclass should subclass TestCase). What is the proper way to group tests for approach B?

© Stack Overflow or respective owner

Related posts about junit

Related posts about automated-tests