Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asserting exception in JUnit [duplicate]

Tags:

java

junit

I need to write a JUnit test case which would test a function passing different permutations,with corresponding results.
A successful used case returns nothing ,while a failed permutation throws exception(exception type wouldnt matter).

eg. testAppleisSweetAndRed(fruit,colour,taste)
The test would invoke the following -

testAppleisSweetAndRed(orange,red,sweet)//throws exception
testAppleisSweetAndRed(apple,green,sweet)//throws exception
testAppleisSweetAndRed(apple,red,sour)//throws exception
testAppleisSweetAndRed(apple,red,sweet)//OK

If the invocations behave as expected,the test succeeds.
How would an assert trap the first 3 invocations to ensure they do raise expected exception?

like image 971
IUnknown Avatar asked Jul 22 '26 02:07

IUnknown


2 Answers

If you are using JUnit 4 or later you can do it as follows. you can use the

@Rule
public ExpectedException exceptions = ExpectedException.none();


this provides a lot of features which can be used to improve our JUnit tests.
If you see the below example I am testing 3 things on the exception.

  1. The Type of exception thrown
  2. The exception Message
  3. The cause of the exception


public class MyTest {

    @Rule
    public ExpectedException exceptions = ExpectedException.none();

    ClassUnderTest testClass;

    @Before
    public void setUp() throws Exception {
        testClass = new ClassUnderTest();
    }

    @Test
    public void testAppleisSweetAndRed() throws Exception {

        exceptions.expect(Exception.class);
        exceptions.expectMessage("this is the exception message");
        exceptions.expectCause(Matchers.<Throwable>equalTo(exceptionCause));

        testClass.appleisSweetAndRed(orange,red,sweet);
    }

}
like image 176
Jobin Avatar answered Jul 24 '26 15:07

Jobin


Tell your test method that what kind of exception your expecting form the test method. you just have to write like below syntax.

@Test(expected = Exception.class) 

It means i am expecting a Exception will be throw from the Test. you can use other exceptions as well like ArrayOutOfBound,etc..

like image 37
Rahul Kumar Avatar answered Jul 24 '26 16:07

Rahul Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!