How to properly check that a method throws a specific exception in JUnit?
Hello everyone! I'm just starting to learn Java and writing unit tests for my project. I have a method that should throw IllegalArgumentException if it receives invalid data. I want to write a test that checks that the exception is actually thrown, but I can't figure out how to do it correctly.
Here's an example of my method:
```java
public class Calculator {
public int divide(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("Divisor cannot be zero");
}
return a / b;
}
}
```
I tried writing the test like this:
```java
@Test
public void testDivideByZero() {
Calculator calc = new Calculator();
calc.divide(10, 0); // Here it just crashes with an exception
}
```
But the test fails
No answers yet.
Log in to leave an answer
Blogs