1

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();

?

Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385

1 Answers1

2

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) { 
        }  
    }  
}  
Kao
  • 7,225
  • 9
  • 41
  • 65