Issue
I'm trying to test if an exception with a customized message is thrown when a division by zero is attempted.
Here's the method:
public static int getMultiplesOfGivenNumber(int number, int[] array){
int multiples = 0;
if (number == 0) {
throw new ArithmeticException("Number cannot be zero");
}else{
for (int i = 0; i < array.length; i++) {
if (array[i] % number == 0) {
multiples += 1;
}
}
}
After searching some solutions, I found this as a way to do the thing, but my IDE can't recognize 'expected' ...
@Test(expected=java.lang.ArithmeticException.class)
public void testDivideByZero(){
//arrange
int number = 0;
//act
int result = B3_E2.getMultiplesOfGivenNumber(number, intervalFromOneToTen());
//assert
assertEquals(expected, result);
}
I'm just unaware why my IDE is not recognizing 'expected'. Don't know if this has something to do with Junit version, or if there's some issue with the syntax I'm using.
In every other tests I used so far I never put nothing after @Test. I just found out this solution in another thread for a similar problem.
Solution
The expected
argument to the @Test
annotation exists only since JUnit 4. You must be using an earlier version of JUnit.
That having been said, you do not have to use this annotation, so you do not have to upgrade to JUnit 4 just for this feature.
You can use a try...catch
yourself, and assert that the exception was thrown, and also assert that the custom message is what it is supposed to be.
@Test
public void testDivideByZero()
{
try
{
B3_E2.getMultiplesOfGivenNumber( 0, intervalFromOneToTen() );
assertTrue( false ); //expected exception was not thrown
}
catch( ArithmeticException e )
{
assertEquals( e.getMessage(), "Number cannot be zero" );
}
}
The benefit of going this way is that you can get your hands on the exception object, so you can examine its contents and make sure that it was initialized as expected. In the case of ArithmeticException
there is nothing to check other than the message, but in other cases there may be a lot more to check.
Answered By - Mike Nakis
Answer Checked By - David Goodson (JavaFixing Volunteer)