PowerMock是一个Java测试框架,用于解决一些传统的Java测试工具无法解决的问题。PowerMock whenNew是PowerMock框架中的一个功能,用于在测试中模拟和控制对特定类构造函数的调用。
当使用PowerMock的whenNew方法时,它允许我们模拟构造函数的行为,并返回我们自定义的模拟对象,而不是实际的对象实例。然而,有时当使用PowerMock whenNew时,它可能无法返回模拟对象。可能会出现以下几种情况:
解决这些问题的方法可能因具体情况而异,但以下是一些常见的解决方案:
总之,PowerMock whenNew用于模拟和控制对特定类构造函数的调用。但在某些情况下,可能会出现无法返回模拟对象的问题,可能是因为PowerMock框架配置不正确、构造函数不可模拟或构造函数中存在无法处理的逻辑。解决这些问题需要细致地检查和调试代码,并根据具体情况采取适当的解决方案。
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.aop.framework.Advised;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.util.ReflectionTestUtils;
@RunWith(PowerMockRunner.class)
@PrepareForTest( { PaymentReconService.class })
@PowerMockIgnore(“org.apache.log4j.*”)
public class PaymentGatherServiceTest extends PaymentServiceTestBase {
@Autowired
private GatherService gatherResultService;
@Autowired
private PaymentBaseDAO baseDAO;
/**
* 测试正常postback
*/
public void testPaymentSucc() {
PaymentReconService mock = mock();
Long pbId = 10004L;
String pbStatus = PaymentBaseEO.PB_STATUS_GATHER_SUCC;
BigDecimal succAmount = new BigDecimal(“99.3”);
try {
GatherOrderRO ro = gatherResultService.processPaymentGather(pbId, pbStatus, succAmount, succAmount);
assertNotNull(ro);
} catch (SystemException e) {
fail(e.getLocalizedMessage());
} catch (BusinessException e) {
fail(e.getBusinessCode());
}
EasyMock.verify(mock);
}
/**
* MOCK PaymentReconService实现
* @return
*/
private PaymentReconService mock() {
PaymentReconRO mockRO = new PaymentReconRO(PaymentReconRO.Status.SUCESS, “OK”);
PaymentReconService mock = EasyMock.createMock(PaymentReconServiceImpl.class);
EasyMock.expect(mock.paymentSuccessRecon(EasyMock.anyObject(Long.class))).andReturn(mockRO);
EasyMock.replay(mock);
//这里把依赖的数据注进去
ReflectionTestUtils.s
领取专属 10元无门槛券
手把手带您无忧上云