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?
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.
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);
}
}
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With