PowerMock 测试私有方法

x33g5p2x  于2021-12-28 转载在 其他  
字(0.7k)|赞(0)|评价(0)|浏览(522)

– Start
假设我们有如下类。

  1. package demo03;
  2. public class BusinessService {
  3. private int max(int a, int b) {
  4. return a > b ? a : b;
  5. }
  6. }

下面我们看看如何测试私有方法。

  1. package demo03;
  2. import org.junit.Assert;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.powermock.core.classloader.annotations.PrepareForTest;
  6. import org.powermock.modules.junit4.PowerMockRunner;
  7. import org.powermock.reflect.Whitebox;
  8. @RunWith(PowerMockRunner.class)
  9. @PrepareForTest({ BusinessService.class })
  10. public class BusinessServiceTest {
  11. @Test
  12. public void test() throws Exception {
  13. BusinessService businessService = new BusinessService();
  14. // 调用私有方法
  15. int max = Whitebox.invokeMethod(businessService, "max", 1, 2);
  16. // 验证
  17. Assert.assertTrue(2 == max);
  18. }
  19. }

– 更多参见:PowerMock 精萃
– 声 明:转载请注明出处
– Last Updated on 2019-08-17
– Written by ShangBo on 2019-08-17
– End

相关文章