PowerMock 调用私有构造函数

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

– Start
假设我们有如下类。

  1. package demo05;
  2. public class BusinessService {
  3. private String serviceName = "";
  4. public BusinessService () {
  5. this("account service");
  6. }
  7. // 私有构造方法
  8. private BusinessService (String serviceName) {
  9. this.serviceName = serviceName;
  10. }
  11. public String getServiceName() {
  12. return serviceName;
  13. }
  14. }

下面我们看看如何调用私有构造函数。

  1. package demo05;
  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. String testServiceName = "test";
  14. // 调用私有构造函数
  15. BusinessService businessService = Whitebox.invokeConstructor(BusinessService.class, testServiceName);
  16. // 验证
  17. Assert.assertEquals(testServiceName, businessService.getServiceName());
  18. }
  19. }

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

相关文章