1

假设我有以下代码:

protected int returnFourtyTwo() {
    evilMethod(new Object, "");
    return 42;
}

protected static void evilMethod(Object obj, String string) {
    throw new RuntimeException("This is me being evil.");
}

我想要做的是运行我的 returnFourtyTwo() 方法而不在我的单元测试中抛出运行时异常。之前我已经能够使用 suppress() 方法绕过类构造函数,但这是我第一次不得不绕过非静态类中的静态方法(具有多个参数)。不幸的是,有关该主题的资源有点稀缺。

4

3 回答 3

1

正如@Dave 所提到的,您唯一的出路是模拟静态方法。您可以使用 PowerMock 做到这一点。

请参阅使用 Mockito 模拟静态方法

于 2015-08-05T16:35:33.700 回答
0

根据您的实际方法实现的复杂程度,您可以将返回调用与异常抛出分开 - 然后测试不会抛出异常的返回调用。在很多情况下,最好是奇怪的整数,例如42无论如何都有自己的变量来解释它对应的内容 - 如果它总是42,那么它是静态的和最终的。

这就是我在这里为您的确切情况所做的事情,但我猜这是对您的实际问题的主要简单抽象,因此您可能仍想按照之前的建议模拟它。

static final int theAnswerToLife = 42;

protected int returnFourtyTwo() {
    evilMethod(new Object, "");
    return getTheAnswerToLife();
}

protected int getTheAnswerToLife() {
    return theAnswerToLife;
}

protected static void evilMethod(Object obj, String string) {
    throw new RuntimeException("This is me being evil.");
}
于 2015-08-05T16:43:18.560 回答
-3

简单来说,您可以对您的方法使用 @Ignore 注释。

于 2015-08-05T17:14:07.543 回答