How to expect exception in constructor with catch-exception?

881 views Asked by At

Is it possible to expect exception in constructor with catch-exception? Can't figure out the syntax. For methods I am writing

catchException(instance).method();

and then, for example

assert caughtException() instanceof IndexOutOfBoundsException;

What should I write for

new MyClass();

?

1

There are 1 answers

2
Kao On

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) { 
        }  
    }  
}