Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit expected tag not working as expected

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

like image 679
Ben S Avatar asked Jul 19 '09 23:07

Ben S


People also ask

What is expected in JUnit?

JUnit provides the facility to trace the exception and also to check whether the code is throwing expected exception or not. Junit4 provides an easy and readable way for exception testing, you can use. Optional parameter (expected) of @test annotation and. To trace the information ,”fail()” can be used.

How do you expect an exception in JUnit?

When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.

How can you use JUnit for testing a code that throws a desired exception?

JUnit provides an option of tracing the exception handling of code. You can test whether the code throws a desired exception or not. The expected parameter is used along with @Test annotation. Let us see @Test(expected) in action.


2 Answers

The problem is that your AnnounceThreadTest 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.

like image 130
Yishai Avatar answered Sep 26 '22 07:09

Yishai


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

@RunWith(JUnit4.class)

like image 27
HsYoo Avatar answered Sep 24 '22 07:09

HsYoo