此外,也有小伙伴推荐 PowerMock 单元测试框架。PowerMock 是 Mockito 的加强版,可以实现完成对private/static/final方法的Mock(模拟)。通过加入 @PrepareForTest 注解来实现。
public class Utility {
private static boolean isGreaterThan(int a, int b) {
return a > b;
}
private Utility() {}
}
/** 测试类 */
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
@RunWith(PowerMockRunner.class)
@PrepareForTest({Utility.class})
public class UtilityTest {
@Test
public void test_privateIsGreaterThan_success() throws Exception {
/** 测试私有的 isGreaterThan 方法 */
boolean result = Whitebox.invokeMethod(Utility.class, "isGreaterThan", 3, 2);
Assertions.assertTrue(result);
}
}