Using catch-exception library, recommended way is to use the builder pattern:
import com.google.common.base.Supplier; // Google Guava
Supplier<MyClass> builder = new Supplier<MyClass>() {
@Override
public MyClass get() {
return new MyClass();
}
};
verifyException(builder).get();
If you are using JUnit 4 for unit testing, you can use Expected Exceptions:
public class TestClass {
@Test(expected = MyException.class)
public void createObjectTest() {
MyClass object = new MyClass();
}
}
In older version of JUnit youd simply catch your exception:
public class TestClass {
@Test
public void createObjectTest() {
try {
MyClass obj = new MyClass();
fail("An exception should be thrown!");
} catch (MyException e) {
}
}
}