如何在Java中使用Hamcrest来测试异常?

问题描述 投票:10回答:4

如何使用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编写的单元测试。

java junit hamcrest
4个回答
23
投票

你真的需要使用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块方法。

6
投票

如果计算断言错误描述(可能这就是为什么Hamcrest不提供这样的功能),我无法以一种很好的方式实现它,但是如果你在Java 8上玩得很好,那么你可能想要这样的东西(但是我不喜欢我认为它会因为下面描述的问题而被使用:

IThrowingRunnable

此接口用于包装可能会抛出异常的代码。也可以使用Callable<E>,但后者需要返回一个值,所以我认为runnable(“void-callable”)更方便。

@FunctionalInterface
public interface IThrowingRunnable<E extends Throwable> {

    void run()
            throws E;

}

FailsWithMatcher

此类实现了一个匹配器,它需要给定的回调来抛出异常。这种实现的一个缺点是让回调抛出一个意外的异常(甚至不抛出一个)并没有描述什么是错的,你会看到完全模糊的错误消息。

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

}

ExceptionMessageMatcher

这是一个示例匹配器,可以对抛出的异常消息进行简单检查。

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

}

And the test sample itself

@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()方法的自定义实现可以解决它。


3
投票

我想最干净的方法是定义一个类似的函数

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之类的东西。


0
投票

除了以上。

如果你将接口更改为... 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 
    ...
© www.soinside.com 2019 - 2024. All rights reserved.