Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test that a constructor throws an exception using JUnit 5?

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

like image 928
TobyBBrown Avatar asked Jan 06 '18 15:01

TobyBBrown


People also ask

How do you test exceptions in JUnit 5?

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.

Can we throw exception in JUnit test?

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.

Can exception be thrown from constructor?

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.


1 Answers

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.

like image 179
Sergey Kalinichenko Avatar answered Nov 15 '22 04:11

Sergey Kalinichenko