如何使用Hamcrest测试异常?根据https://code.google.com/p/hamcrest/wiki/Tutorial的评论,“Junit 4使用期望的属性提供了异常处理。”
所以我尝试了这个,发现它有效:
public class MyObjectifyUtilTest {
@Test
public void shouldFindFieldByName() throws MyObjectifyNoSuchFieldException {
String fieldName = "status";
String field = MyObjectifyUtil.getField(DownloadTask.class, fieldName);
assertThat(field, equalTo(fieldName));
}
@Test(expected=MyObjectifyNoSuchFieldException.class)
public void shouldThrowExceptionBecauseFieldDoesNotExist() throws MyObjectifyNoSuchFieldException {
String fieldName = "someMissingField";
String field = MyObjectifyUtil.getField(DownloadTask.class, fieldName);
assertThat(field, equalTo(fieldName));
}
}
Hamcrest是否提供了来自JUnit的@Test(expected=...)
注释之外的任何其他功能?
虽然有人在Groovy(How to use Hamcrest to test for exception?)中询问过这个问题,但我的问题是用Java编写的单元测试。
你真的需要使用Hamcrest
库吗?
如果没有,这里是你如何使用Junit
支持异常测试。 ExpectedException
类有很多方法可以用来做你想要的,除了检查抛出的Exception
的类型。
您可以将Hamcrest
匹配器与此结合使用来声明特定的内容,但最好让Junit
期望抛出异常。
public class MyObjectifyUtilTest {
// create a rule for an exception grabber that you can use across
// the methods in this test class
@Rule
public ExpectedException exceptionGrabber = ExpectedException.none();
@Test
public void shouldThrowExceptionBecauseFieldDoesNotExist() throws MyObjectifyNoSuchFieldException {
String fieldName = "someMissingField";
// a method capable of throwing MyObjectifyNoSuchFieldException too
doSomething();
// assuming the MyObjectifyUtil.getField would throw the exception,
// I'm expecting an exception to be thrown just before that method call
exceptionGrabber.expect(MyObjectifyNoSuchFieldException.class);
MyObjectifyUtil.getField(DownloadTask.class, fieldName);
...
}
}
这种方法比
@Test (expected=...)
方法因为@Test (expected=...)
只测试方法执行是否通过抛出给定的异常而停止,而不是如果你想抛出异常的调用抛出一个。例如,即使doSomething
方法抛出可能不合需要的MyObjectifyNoSuchFieldException
异常,测试也会成功try/catch
块方法。如果计算断言错误描述(可能这就是为什么Hamcrest不提供这样的功能),我无法以一种很好的方式实现它,但是如果你在Java 8上玩得很好,那么你可能想要这样的东西(但是我不喜欢我认为它会因为下面描述的问题而被使用:
此接口用于包装可能会抛出异常的代码。也可以使用Callable<E>
,但后者需要返回一个值,所以我认为runnable(“void-callable”)更方便。
@FunctionalInterface
public interface IThrowingRunnable<E extends Throwable> {
void run()
throws E;
}
此类实现了一个匹配器,它需要给定的回调来抛出异常。这种实现的一个缺点是让回调抛出一个意外的异常(甚至不抛出一个)并没有描述什么是错的,你会看到完全模糊的错误消息。
public final class FailsWithMatcher<EX extends Throwable>
extends TypeSafeMatcher<IThrowingRunnable<EX>> {
private final Matcher<? super EX> matcher;
private FailsWithMatcher(final Matcher<? super EX> matcher) {
this.matcher = matcher;
}
public static <EX extends Throwable> Matcher<IThrowingRunnable<EX>> failsWith(final Class<EX> throwableType) {
return new FailsWithMatcher<>(instanceOf(throwableType));
}
public static <EX extends Throwable> Matcher<IThrowingRunnable<EX>> failsWith(final Class<EX> throwableType, final Matcher<? super EX> throwableMatcher) {
return new FailsWithMatcher<>(allOf(instanceOf(throwableType), throwableMatcher));
}
@Override
protected boolean matchesSafely(final IThrowingRunnable<EX> runnable) {
try {
runnable.run();
return false;
} catch ( final Throwable ex ) {
return matcher.matches(ex);
}
}
@Override
public void describeTo(final Description description) {
description.appendText("fails with ").appendDescriptionOf(matcher);
}
}
这是一个示例匹配器,可以对抛出的异常消息进行简单检查。
public final class ExceptionMessageMatcher<EX extends Throwable>
extends TypeSafeMatcher<EX> {
private final Matcher<? super String> matcher;
private ExceptionMessageMatcher(final Matcher<String> matcher) {
this.matcher = matcher;
}
public static <EX extends Throwable> Matcher<EX> exceptionMessage(final String message) {
return new ExceptionMessageMatcher<>(is(message));
}
@Override
protected boolean matchesSafely(final EX ex) {
return matcher.matches(ex.getMessage());
}
@Override
public void describeTo(final Description description) {
description.appendDescriptionOf(matcher);
}
}
@Test
public void test() {
assertThat(() -> emptyList().get(0), failsWith(IndexOutOfBoundsException.class, exceptionMessage("Index: 0")));
assertThat(() -> emptyList().set(0, null), failsWith(UnsupportedOperationException.class));
}
注意这种方法:
最糟糕的是,典型的失败会是这样的
java.lang.AssertionError:
Expected: fails with (an instance of java.lang.IndexOutOfBoundsException and is "Index: 0001")
but: was <foo.bar.baz.FailsWithMatcherTest$$Lambda$1/127618319@6b143ee9>
也许使用assertThat()
方法的自定义实现可以解决它。
我想最干净的方法是定义一个类似的函数
public static Throwable exceptionOf(Callable<?> callable) {
try {
callable.call();
return null;
} catch (Throwable t) {
return t;
}
}
某处然后例如呼叫
assertThat(exceptionOf(() -> callSomethingThatShouldThrow()),
instanceOf(TheExpectedException.class));
也许还使用像this answer的ExceptionMessageMatcher之类的东西。
除了以上。
如果你将接口更改为... extends Exception,你可以像这样抛出一个错误:
@Override
protected boolean matchesSafely(final IThrowingRunnable<EX> runnable) {
try {
runnable.run();
throw new Error("Did not throw Exception");
} catch (final Exception ex) {
return matcher.matches(ex);
}
}
跟踪将如下所示:
java.lang.Error: Did not throw Exception
at de.test.test.FailsWithMatcher.matchesSafely(FailsWithMatcher.java:31)
at de.test.test.FailsWithMatcher.matchesSafely(FailsWithMatcher.java:1)
at org.hamcrest.TypeSafeMatcher.matches(TypeSafeMatcher.java:65)
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:12)
at org.junit.Assert.assertThat(Assert.java:956)
at org.junit.Assert.assertThat(Assert.java:923)
at
...