我是Mockito和PowerMockito的新手。我發現我不能用純Mockito測試靜態方法,所以我需要用戶PowerMockito(對吧?)。爲什麼我應該嘲笑?
我有一個名爲驗證與此非常簡單的方法
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類和我檢查,當模擬被稱爲與null參數爲對象,以及任何字符串作爲消息的方法,則拋出IllegalStateException。
現在,我真的不明白。爲什麼我不能直接調用這個方法,放棄整個巫術魔法來嘲弄那個靜態類?在我看來,除非我調用Validate.stateNotNull測試通過...爲什麼我應該嘲笑它?