– Start
假设我们有如下类。
package demo05;
public class BusinessService {
private String serviceName = "";
public BusinessService () {
this("account service");
}
// 私有构造方法
private BusinessService (String serviceName) {
this.serviceName = serviceName;
}
public String getServiceName() {
return serviceName;
}
}
下面我们看看如何调用私有构造函数。
package demo05;
import org.junit.Assert;
import org.junit.Test;
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({ BusinessService.class })
public class BusinessServiceTest {
@Test
public void test() throws Exception {
String testServiceName = "test";
// 调用私有构造函数
BusinessService businessService = Whitebox.invokeConstructor(BusinessService.class, testServiceName);
// 验证
Assert.assertEqual

本文介绍了如何在Java中使用PowerMock框架来调用类的私有构造函数,提供了一个示例代码,并提醒读者更多内容可以参考PowerMock的相关精粹。
最低0.47元/天 解锁文章
2892

被折叠的 条评论
为什么被折叠?



