PowerMock 抑制运行静态块

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

– Start
假设我们有如下类。

  1. package demo07;
  2. public class BusinessService {
  3. private static String serviceName;
  4. static {
  5. serviceName = "test";
  6. }
  7. public String getServiceName() {
  8. return serviceName;
  9. }
  10. }

下面我们看看如何测试。

  1. package demo07;
  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.core.classloader.annotations.SuppressStaticInitializationFor;
  7. import org.powermock.modules.junit4.PowerMockRunner;
  8. @RunWith(PowerMockRunner.class)
  9. @PrepareForTest({ BusinessService.class })
  10. @SuppressStaticInitializationFor("demo07.BusinessService")
  11. public class BusinessServiceTest {
  12. @Test
  13. public void test() throws Exception {
  14. // 不调用构造函数
  15. BusinessService businessService = new BusinessService();
  16. // 验证
  17. Assert.assertNull(businessService.getServiceName());
  18. }
  19. }

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

相关文章