2

I managed it to understand Junit 3.8 but honestly I have no idea how junit 4 works even after I read documentations for more than 45 minutes. I don't have a problem with the annotations but with running the tests. For example junit won't find my expected exception in this little example:

Output:

.E
Time: 0,011
There was 1 error:
1)     testTest(junittests.TestTestCase)java.util.InputMismatchException

Main.java

TestRunner.run(TestTestCase.class);

DemoClass.java

import java.util.InputMismatchException;

public class DemoClass {
    public void test() {
        throw new InputMismatchException();
    }
}

TestTestCase.java

import junit.framework.TestCase;
import org.junit.Before;

import java.util.InputMismatchException;

public class TestTestCase extends TestCase {
    private DemoClass inst;
    @Before
    public void setUp() {
        inst = new DemoClass();
    }
    @org.junit.Test(expected = InputMismatchException.class)
    public void testTest() {
        inst.test();
    }
}

I really have no clue how to use it. Thanks a lot in advance!

sisyphus
  • 6,174
  • 1
  • 25
  • 35
phip1611
  • 5,460
  • 4
  • 30
  • 57
  • 5
    Don't extend TestCase. Don't use any class from the junit.framework package. They're there to be able to run legacy JUnit 3 tests. They shouldn't be used in JUnit 4. – JB Nizet Apr 30 '16 at 22:15
  • 1
    Can confirm, was able to recreate the problem. Removing the ```extends TestCase``` solved it. – Jorn Vernee Apr 30 '16 at 22:16
  • hi guys! When I remove the `extends Test Case` the line `TestRunner.run(TestTestCase.class);` produces a error. "No suitable method found for run". I guess I need another Runner-Class but which one? – phip1611 Apr 30 '16 at 22:20
  • tbh I always use the eclipse JUnit launcher. But [this question](http://stackoverflow.com/questions/2235276/how-to-run-junit-test-cases-from-the-command-line) suggested using ```org.junit.runner.JUnitCore```. I tried ```JUnitCore.runClasses(DemoClassTest.class);```, It returns a ```Result``` object which you can query for information. – Jorn Vernee Apr 30 '16 at 22:45
  • Thanks a lot! Does this mean in junit 4 I'm not longer using textui/awtui/swingui? – phip1611 Apr 30 '16 at 23:27

1 Answers1

0

Try it like this:

Your test class.

public class DemoClass {
    public void test() {
        throw new InputMismatchException();
    }
}

Test class in the same package:

public class DemoClassTest {
    @Test(expected = InputMismatchException.class)
    public void testTest() {
        new DemoClass().test();
    }
}

I can run this all day in IntelliJ.

duffymo
  • 305,152
  • 44
  • 369
  • 561