我也是 Mockito 和 PowerMockito 的新手。我发现我无法使用纯 Mockito 测试静态方法,所以我需要使用 PowerMockito(对吗?)。
我有一个非常简单的类,叫做 Validate 用这个非常简单的方法
public class Validate {
public final static void stateNotNull(
final Object object,
final String message) {
if (message == null) {
throw new IllegalArgumentException("Exception message is a null object!");
}
if (object == null) {
throw new IllegalStateException(message);
}
}
所以我需要验证:
1)当我在空消息参数上调用该静态方法时,会调用 IllegalArgumentException
2)当我在空对象参数上调用该静态方法时,会调用 IllegalStateException
从我目前得到的,我写了这个测试:
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.isNull;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.testng.annotations.Test;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Validate.class)
public class ValidateTestCase {
@Test(expectedExceptions = { IllegalStateException.class })
public void stateNotNullTest() throws Exception {
PowerMockito.mockStatic(Validate.class);
Validate mock = PowerMockito.mock(Validate.class);
PowerMockito.doThrow(new IllegalStateException())
.when(mock)
.stateNotNull(isNull(), anyString());
Validate.stateNotNull(null, null);
}
}
所以这表示我模拟了 Validate 类,并且我正在检查当在该方法上调用 mock 时,使用 null 参数作为对象,任何字符串作为消息,抛出 IllegalStateException。
现在,我真的不明白。为什么我不能直接调用那个方法,放弃整个巫术魔法来模拟那个静态类?在我看来,除非我调用 Validate.stateNotNull,否则测试无论如何都会通过......我应该模拟它的原因是什么?