我知道可以在JUnit中定义'预期'异常,执行:
@Test(expect=MyException.class)
public void someMethod() { ... }
但是如果总是抛出相同的异常,但是使用不同的'嵌套'会怎么样? 的引起
有什么建议吗?
答案 0 :(得分:81)
从JUnit 4.11开始,您可以使用ExpectedException
规则的expectCause()
方法:
import static org.hamcrest.CoreMatchers.*;
// ...
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void throwsNestedException() throws Exception {
expectedException.expectCause(isA(SomeNestedException.class));
throw new ParentException("foo", new SomeNestedException("bar"));
}
答案 1 :(得分:23)
您可以将测试代码包装在try / catch块中,捕获抛出的异常,检查内部原因,log / assert / whatever,然后重新抛出异常(如果需要)。
答案 2 :(得分:7)
如果您使用的是最新版本的JUnit,您可以扩展默认测试运行器来为您处理(无需将每个方法包装在try / catch块中)
ExtendedTestRunner.java - 新的测试运行器:
public class ExtendedTestRunner extends BlockJUnit4ClassRunner
{
public ExtendedTestRunner( Class<?> clazz )
throws InitializationError
{
super( clazz );
}
@Override
protected Statement possiblyExpectingExceptions( FrameworkMethod method,
Object test,
Statement next )
{
ExtendedTest annotation = method.getAnnotation( ExtendedTest.class );
return expectsCauseException( annotation ) ?
new ExpectCauseException( next, getExpectedCauseException( annotation ) ) :
super.possiblyExpectingExceptions( method, test, next );
}
@Override
protected List<FrameworkMethod> computeTestMethods()
{
Set<FrameworkMethod> testMethods = new HashSet<FrameworkMethod>( super.computeTestMethods() );
testMethods.addAll( getTestClass().getAnnotatedMethods( ExtendedTest.class ) );
return testMethods;
}
@Override
protected void validateTestMethods( List<Throwable> errors )
{
super.validateTestMethods( errors );
validatePublicVoidNoArgMethods( ExtendedTest.class, false, errors );
}
private Class<? extends Throwable> getExpectedCauseException( ExtendedTest annotation )
{
if (annotation == null || annotation.expectedCause() == ExtendedTest.None.class)
return null;
else
return annotation.expectedCause();
}
private boolean expectsCauseException( ExtendedTest annotation) {
return getExpectedCauseException(annotation) != null;
}
}
ExtendedTest.java - 用以下标记标记测试方法的注释:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface ExtendedTest
{
/**
* Default empty exception
*/
static class None extends Throwable {
private static final long serialVersionUID= 1L;
private None() {
}
}
Class<? extends Throwable> expectedCause() default None.class;
}
ExpectCauseException.java - 新的JUnit语句:
public class ExpectCauseException extends Statement
{
private Statement fNext;
private final Class<? extends Throwable> fExpected;
public ExpectCauseException( Statement next, Class<? extends Throwable> expected )
{
fNext= next;
fExpected= expected;
}
@Override
public void evaluate() throws Exception
{
boolean complete = false;
try {
fNext.evaluate();
complete = true;
} catch (Throwable e) {
if ( e.getCause() == null || !fExpected.isAssignableFrom( e.getCause().getClass() ) )
{
String message = "Unexpected exception cause, expected<"
+ fExpected.getName() + "> but was<"
+ ( e.getCause() == null ? "none" : e.getCause().getClass().getName() ) + ">";
throw new Exception(message, e);
}
}
if (complete)
throw new AssertionError( "Expected exception cause: "
+ fExpected.getName());
}
}
用法:
@RunWith( ExtendedTestRunner.class )
public class MyTests
{
@ExtendedTest( expectedCause = MyException.class )
public void someMethod()
{
throw new RuntimeException( new MyException() );
}
}
答案 3 :(得分:6)
您可以随时手动执行此操作:
@Test
public void someMethod() {
try{
... all your code
} catch (Exception e){
// check your nested clauses
if(e.getCause() instanceof FooException){
// pass
} else {
Assert.fail("unexpected exception");
}
}
答案 4 :(得分:5)
您可以为例外创建Matcher。即使您使用Arquillian @RunWith(Arquillian.class)
之类的其他测试运行器,也可以使用上面建议的@RunWith(ExtendedTestRunner.class)
方法。
这是一个简单的例子:
public class ExceptionMatcher extends BaseMatcher<Object> {
private Class<? extends Throwable>[] classes;
// @SafeVarargs // <-- Suppress warning in Java 7. This usage is safe.
public ExceptionMatcher(Class<? extends Throwable>... classes) {
this.classes = classes;
}
@Override
public boolean matches(Object item) {
for (Class<? extends Throwable> klass : classes) {
if (! klass.isInstance(item)) {
return false;
}
item = ((Throwable) item).getCause();
}
return true;
}
@Override
public void describeTo(Description descr) {
descr.appendText("unexpected exception");
}
}
然后将其与@Rule和ExpectedException一起使用,如下所示:
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testSomething() {
thrown.expect(new ExceptionMatcher(IllegalArgumentException.class, IllegalStateException.class));
throw new IllegalArgumentException("foo", new IllegalStateException("bar"));
}
由Craig Ringer于2012年添加编辑:增强且更可靠的版本:
boolean rethrow
来抛出不匹配的异常。这样可以保留嵌套异常的堆栈跟踪,以便于调试。@SaveVarargs
。完整代码:
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
public class ExceptionMatcher extends BaseMatcher<Object> {
private Class<? extends Throwable>[] acceptedClasses;
private Throwable[] nestedExceptions;
private final boolean rethrow;
@SafeVarargs
public ExceptionMatcher(Class<? extends Throwable>... classes) {
this(false, classes);
}
@SafeVarargs
public ExceptionMatcher(boolean rethrow, Class<? extends Throwable>... classes) {
this.rethrow = rethrow;
this.acceptedClasses = classes;
}
@Override
public boolean matches(Object item) {
nestedExceptions = ExceptionUtils.getThrowables((Throwable)item);
for (Class<? extends Throwable> acceptedClass : acceptedClasses) {
for (Throwable nestedException : nestedExceptions) {
if (acceptedClass.isInstance(nestedException)) {
return true;
}
}
}
if (rethrow) {
throw new AssertionError(buildDescription(), (Throwable)item);
}
return false;
}
private String buildDescription() {
StringBuilder sb = new StringBuilder();
sb.append("Unexpected exception. Acceptable (possibly nested) exceptions are:");
for (Class<? extends Throwable> klass : acceptedClasses) {
sb.append("\n ");
sb.append(klass.toString());
}
if (nestedExceptions != null) {
sb.append("\nNested exceptions found were:");
for (Throwable nestedException : nestedExceptions) {
sb.append("\n ");
sb.append(nestedException.getClass().toString());
}
}
return sb.toString();
}
@Override
public void describeTo(Description description) {
description.appendText(buildDescription());
}
}
典型输出:
java.lang.AssertionError: Expected: Unexpected exception. Acceptable (possibly nested) exceptions are:
class some.application.Exception
Nested exceptions found were:
class javax.ejb.EJBTransactionRolledbackException
class javax.persistence.NoResultException
got: <javax.ejb.EJBTransactionRolledbackException: getSingleResult() did not retrieve any entities.>
答案 5 :(得分:4)
为此,我写了一个小JUnit扩展。静态辅助函数接受函数体和一系列预期的异常:
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Arrays;
public class AssertExt {
public static interface Runnable {
void run() throws Exception;
}
public static void assertExpectedExceptionCause( Runnable runnable, @SuppressWarnings("unchecked") Class[] expectedExceptions ) {
boolean thrown = false;
try {
runnable.run();
} catch( Throwable throwable ) {
final Throwable cause = throwable.getCause();
if( null != cause ) {
assertTrue( Arrays.asList( expectedExceptions ).contains( cause.getClass() ) );
thrown = true;
}
}
if( !thrown ) {
fail( "Expected exception not thrown or thrown exception had no cause!" );
}
}
}
您现在可以检查预期的嵌套异常,如下所示:
import static AssertExt.assertExpectedExceptionCause;
import org.junit.Test;
public class TestExample {
@Test
public void testExpectedExceptionCauses() {
assertExpectedExceptionCause( new AssertExt.Runnable(){
public void run() throws Exception {
throw new Exception( new NullPointerException() );
}
}, new Class[]{ NullPointerException.class } );
}
}
这可以节省您一次又一次地编写相同的锅炉铭牌代码。
答案 6 :(得分:1)
最简洁的语法由catch-exception提供:
import static com.googlecode.catchexception.CatchException.*;
catchException(myObj).doSomethingNasty();
assertTrue(caughtException().getCause() instanceof MyException);
答案 7 :(得分:0)
在 JUnit5 中,您可以使用 assertThrows
方法,除了断言抛出的异常之外,它还返回它,以便您可以对其执行其他断言。
@Test
void test() {
// Assert that parent exception is thrown and retrieve it
ParentException parentException = assertThrows(ParentException.class, () -> methodThatThrowsException());
// Perform assertions on the cause
Throwable cause = parentException.getCause();
assertThat(cause, ...);
}
void methodThatThrowsException() {
throw new ParentException("foo", new SomeNestedException("bar"));
}