我是新手,对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 类,并检查当该方法被调用时,如果使用空对象作为参数和任何字符串作为消息,则会抛出 IllegalStateException 异常。
现在,我真的不明白。为什么我不能直接调用该方法,放弃围绕静态类进行模拟的整个神秘魔法?似乎除非我调用 Validate.stateNotNull 方法,否则测试都会通过... 我为什么要模拟它呢?