I'm making a Fraction API class, one of my constructors normalises a fraction by putting the numerator and denominator parameters in their lowest terms:
public Fraction(int numerator, int denominator){
if (denominator == 0)
throw new ArithmeticException("Cannot divide by zero.");
else {
if (denominator < 0) {
numerator = -numerator;
denominator = -denominator;
}
int gcd; // Greatest Common Divisor
int tmpNum = numerator, tmpDen = denominator;
// Determine greatest common divisor of numerator and denominator
while (tmpNum != 0 && tmpDen != 0) {
int tmp = tmpDen;
tmpDen = tmpNum % tmpDen;
tmpNum = tmp;
}
gcd = Math.abs(tmpNum + tmpDen);
this.numerator = numerator / gcd; // Assign numerator in its lowest term
this.denominator = denominator / gcd; // Assign denominator in its lowest term
}
}
I want to test that the constructor throws an ArithmeticException when the denominator is 0. As far as I can tell JUnit 5 does not support @Test(expected = ArithmeticException.class
but uses assertThrows()
.
My test:
@Test
public void testZeroDenominator(){
Fraction f;
assertThrows(ArithmeticException.class, f = new Fraction(2, 0));
}
does not work and IntelliJ says 'Fraction is not compatible with Executable'.
How can I test that the constructor throws the exception?
Thanks
In JUnit 5, to write the test code that is expected to throw an exception, we should use Assertions. assertThrows(). In the given test, the test code is expected to throw an exception of type ApplicationException or its subtype. Note that in JUnit 4, we needed to use @Test(expected = NullPointerException.
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.
The short answer to the question “can a constructor throw an exception in Java” is yes! Of course, properly implementing exceptions in your constructors is essential to getting the best results and optimizing your code.
Here is the syntax to pass lambda for JUnit 5's Executable
:
assertThrows(ArithmeticException.class, () -> new Fraction(2, 0));
You don't need to assign the result to f
, because you know that the method is not going to complete.
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