Note that there are some explanatory texts on larger screens.

plurals
  1. POJUnit confusion: use 'extends TestCase' or '@Test'?
    text
    copied!<p>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.</p> <p>If I've understood correctly, there are two main approaches to create and run a JUnit test:</p> <p><strong>Approach A (JUnit 3-style):</strong> create a class that extends TestCase, and start test methods with the word <code>test</code>. When running the class as a JUnit Test (in Eclipse), all methods starting with the word <code>test</code> are automatically run.</p> <pre><code>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); } } </code></pre> <p><strong>Approach B (JUnit 4-style):</strong> create a 'normal' class and prepend a <code>@Test</code> annotation to the method. Note that you do NOT have to start the method with the word <code>test</code>.</p> <pre><code>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); } } </code></pre> <p>Mixing the two seems not to be a good idea, see e.g. <a href="https://stackoverflow.com/questions/1151237/junit-expected-tag-not-working-as-expected">this stackoverflow question</a>: </p> <p>Now, my questions(s):</p> <ol> <li><strong>What is the preferred approach</strong>, or when would you use one instead of the other?</li> <li>Approach B allows for testing for exceptions by extending the @Test annotation like in <code>@Test(expected = ArithmeticException.class)</code>. <strong>But how do you test for exceptions when using approach A?</strong></li> <li><p>When using approach A, you can group a number of test classes in a test suite like this:</p> <p><code>TestSuite suite = new TestSuite("All tests");</code><br/> <code>suite.addTestSuite(DummyTestA.class);</code><br/> <code>suite.addTestSuite(DummyTestAbis.class);</code><br/><br/> But this can't be used with approach B (since each testclass should subclass TestCase). <strong>What is the proper way to group tests for approach B?</strong></p></li> </ol> <p>Edit: I've added the JUnit versions to both approaches</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload