50

I have the following test case in eclipse, using JUnit 4 which is refusing to pass. What could be wrong?

@Test(expected = IllegalArgumentException.class)
public void testIAE() {
    throw new IllegalArgumentException();
}

This exact testcase came about when trying to test my own code with the expected tag didn't work. I wanted to see if JUnit would pass the most basic test. It didn't.

I've also tested with custom exceptions as expected without luck.

Screenshot: Screenshot

2
  • 2
    This one is really weird, did some testing myself, and this code runs fine (the test is successfull)...
    – Torandi
    Jul 20, 2009 at 0:22
  • I added a screenshot, just to show... I'd be doubtful too.
    – Ben S
    Jul 20, 2009 at 1:17

3 Answers 3

103

The problem is that your nnounceThreadTest extends TestCase. Because it extends TestCase, the JUnit Runner is treating it as a JUnit 3.8 test, and the test is running because it starts with the word test, hiding the fact that the @Test annotiation is in fact not being used at all.

To fix this, remove the extends TestCase from the class definition.

7
  • Thank you, this fixed it as advertised.
    – Ben S
    Jul 20, 2009 at 1:24
  • 5
    After removing the extends TestCase, I had to add the additional import to ensure I had the static assert methods. import static org.junit.Assert.*;
    – burtlo
    Jul 26, 2009 at 21:58
  • 9
    Awesome job at finding the solution hidden as a hint in a screenshot
    – matt b
    Mar 17, 2010 at 12:47
  • Solved!! Thank you, saved me some time.
    – Patelify
    Dec 12, 2011 at 23:47
  • Argggghhhh, I just spent an hour and a half on this issue without finding this answer. Thank you, thank you, thank you! Oct 10, 2014 at 17:27
4

Instead of removing extends TestCase , you can add this to run your test case with Junit4 which supports annotation.

@RunWith(JUnit4.class)

3

Just ran this in IntelliJ using JUnit 4.4:

   @Test(expected = IllegalArgumentException.class)
   public void testExpected()
   {
       throw new IllegalArgumentException();
   }

Passes perfectly.

Rebuild your entire project and try again. There's something else that you're doing wrong. JUnit 4.4 is working as advertised.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.