在自定义字段中使用特定条件声明期望的异常

问题描述 投票:1回答:1

我想验证预期的例外是否符合某些条件。以此为起点:

class MyException extends RuntimeException {
    int n;
    public MyException(String message, int n) {
        super(message);
        this.n = n;
    }
}

public class HowDoIDoThis {
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void test1() {
        thrown.expect(MyException.class);
        throw new MyException("x", 10);
    }
}

例如,如何断言抛出的异常具有n > 1,并且message仅包含小写字母?我当时在考虑使用thrown.expect(Matcher),但无法弄清楚如何使Hamcrest匹配器检查对象的任意字段。

java junit junit4 hamcrest
1个回答
0
投票

您可以使用TypeSafeMatcher在其中提供您的MyException类,然后使用IntPredicate根据条件检查n值:

public class MyExceptionMatcher extends TypeSafeMatcher<MyException> {
    private final IntPredicate predicate;

    public MyExceptionMatcher(IntPredicate predicate) {
        this.predicate = predicate;
    }

    @Override
    protected boolean matchesSafely(MyException item) {
        return predicate.test(item.n);
    }

    @Override
    public void describeTo(Description description) {
        description.appendText("my exception which matches predicate");
    }
}

然后您可以期望这样:

thrown.expect(new MyExceptionMatcher(i -> i > 1));
© www.soinside.com 2019 - 2024. All rights reserved.