PowerMock 不调用构造函数

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

– Start
假设我们有如下类。

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

下面我们看看如何不调用构造函数创建对象。

  1. package demo06;
  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. // 不调用构造函数
  14. BusinessService businessService = Whitebox.newInstance(BusinessService.class);
  15. // 验证
  16. Assert.assertNull(businessService.getServiceName());
  17. }
  18. }

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

相关文章