[英]How to expect exception in constructor with catch-exception?
Is it possible to expect exception in constructor with catch-exception
? 是否可以在具有catch-exception
构造函数中期望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();
? ?
Using catch-exception library, recommended way is to use the builder pattern: 使用catch-exception库, 建议的方法是使用构建器模式:
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 : 如果将JUnit 4用于单元测试,则可以使用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: 在旧版本的JUnit中,您只需捕获异常即可:
public class TestClass {
@Test
public void createObjectTest() {
try {
MyClass obj = new MyClass();
fail("An exception should be thrown!");
} catch (MyException e) {
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.