私は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) null メッセージ引数でその静的メソッドを呼び出すと、IllegalArgumentException が呼び出されます
2) null オブジェクト引数でその静的メソッドを呼び出すと、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 を呼び出さない限り、テストに合格するように思えます...どのような理由でそれをモックする必要がありますか?