I'm trying to get into testing using JUnit and I struggle to understand what I'm doing wrong. I made something pretty simple:
A class that should be able to create something. So far I'm just testing if the object it gets is null or not.
public class TestedClass {
public void create(Object o) {
if (o == null) {
throw new IllegalArgumentException();
} else {
System.out.println("Not null!");
}
}
}
The tester class, it creates a new TestedClass object and tries to create something with null. It expects a IllegalArgumentException.
import org.junit.Test;
public class Tester {
@Test(expected = IllegalArgumentException.class)
public void createWithNullShouldThrowException() {
TestedClass t = new TestedClass();
t.create(null);
}
}
Just the main class.
public class Main {
public static void main(String[] args) {
Tester test = new Tester();
test.createWithNullShouldThrowException();
System.out.println("passed all tests!");
}
}
The way I understand it, it should terminate properly if there's an IllegalArgumentException thrown during the whole testing procedure. Which is the case as my program is terminating with:
Exception in thread "main" java.lang.IllegalArgumentException
at TestedClass.create(TestedClass.java:4)
at Tester.createWithNullShouldThrowException(Tester.java:6)
at Main.main(Main.java:7)
Which shouldn't happen since it should get caught by the createWithNullShouldThrowException() method in the Tester class, or am I not understanding this correctly? I know that I could probably do this with a try catch block instead but I just want to know what's wrong in this case. If it's any help, I'm using IntelliJ IDEA 16.1. Any help would be appreciated.