如何使用Power mockito在公共类中模拟静态方法?

时间:2017-09-21 08:15:02

标签: java unit-testing junit mocking powermock

您好我试图模拟一个静态方法名称 mapCreditInfo(UCIPin,creditAssessmentResults),它有两个参数 UCIPin creditAssessmentResults 。 UCIPin是String类型,creditAssessmentResults是List 此方法位于公共类ResponseMapper中 输入如下所示:

private CreditInfo getAccountByUCI(String audiUser, String UCIPin) throws EnterpriseCustomerVerificationException {
    List<CreditAssessmentResult> creditAssessmentResults = creditInfoRepository.getUCISummary(UCIPin, audiUser);
    return ResponseMapper.mapCreditInfo(UCIPin, creditAssessmentResults);
}
  

注意:在另一个公共方法中调用getAccountbyUCI方法   名称 executeCustomerVerification ,它在类中   的 EnterpriseCustomerVerificationService

ResponseMapper类

public class ResponseMapper {

public static CreditInfo mapCreditInfo(String UCIPin, List<CreditAssessmentResult> creditAssessmentResults) {
    CreditInfo creditInfo = new CreditInfo();

    creditInfo.setUCIPin(UCIPin);

    List<AccountCreditInfo> accountCreditInfos = new ArrayList<AccountCreditInfo>();
    for (CreditAssessmentResult creditAssessmentResult : creditAssessmentResults) {
        AccountCreditInfo accountCreditInfo = new AccountCreditInfo();
        accountCreditInfo.setDelinquenctBalance(creditAssessmentResult.getPastDueAmount());
        accountCreditInfo.setNonPayDisconnect(creditAssessmentResult.getNonpayDiscount());
        accountCreditInfo.setPreviousAccountNumber(creditAssessmentResult.getAccountNumber());
        accountCreditInfo.setUnreturnedEquipmentFlag(creditAssessmentResult.getUnreturnedEquipment());

        accountCreditInfos.add(accountCreditInfo);
    }
    creditInfo.setAccountCreditInfo(accountCreditInfos);

    return creditInfo;
}

}

我试过我的测试类的某些部分,如下所示: 测试类

@PrepareForTest( EnterpriseCustomerVerificationService.class)
@RunWith(PowerMockRunner.class)
public class EnterpriseCustomerVerificationServiceTest {

@InjectMocks
    private EnterpriseCustomerVerificationService enterpriseCustormerVerificationServiceMock ;
@Test
public void executeCustomerVerificationTest() throws Exception {
    List<ErrorResponse> errorResponses = getErrorResponse();
    List<String> mso = new ArrayList<String>();
    mso.add("a");
    mso.add("b");
    mso.add("c");
    AddressResponse addressResponse = getAddressResponse();
    String experianAuthorization = "experianAuthorization";
    String UCIPin = "110019";
    String auditUser = "ABC";

    CreditInfo credit  =   getCreditInfo();
    CreditCheck creditCheck = getcreditCheck();
    EnterpriseCustomerVerificationService spy = PowerMockito.spy(new EnterpriseCustomerVerificationService());

    PowerMockito.when(spy,PowerMockito.method(EnterpriseCustomerVerificationService.class,"executeCreditCheck",CreditCheck.class)).withArguments(Mockito.any()).thenReturn("@1");
    Mockito.when(creditInfoRepository.getUCISummary("110019", "test")).thenReturn(getCreditAssessmentResultList());

    PowerMockito.mockStatic(ResponseMapper.class);
    Mockito.when(ResponseMapper.mapCreditInfo(UCIPin, getCreditAssessmentResultList())).thenReturn(credit);

    CustomerVerification cv = spy
            .executeCustomerVerification(getCustomerVerificationRequest1(),
                    "101");
}

我的问题是如何使用power Mockito模拟静态mapCreditInfo 方法?

由于

2 个答案:

答案 0 :(得分:1)

喜欢这个......

@RunWith(PowerMockRunner.class)
@PrepareForTest({ResponseMapper.class})
public class ATest {

    @Test
    public void testMockingStatic() {
        PowerMockito.mockStatic(ResponseMapper.class);

        // if you want to use specific argument matchers
        Mockito.when(ResponseMapper.mapCreditInfo(
            uciPin, creditAssessmentResults)
        ).thenReturn(creditInfo);

        // or if you want to match on any arguments passed into your static method ...
        Mockito.when(ResponseMapper.mapCreditInfo(
            ArgumentMatchers.anyString(), 
            ArgumentMatchers.anyList())
        ).thenReturn(creditInfo);

        // ...
    }
}

注意:

  • @PrepareForTest使用您想要模拟的静态方法准备类
  • PowerMockito.mockStatic模拟类
  • 的所有静态方法
  • 您可以使用标准Mockito /然后构造告诉模拟的静态方法返回什么
  • 上面的示例使用这些依赖项:
    • org.mockito:mockito-core:2.7.19
    • org.powermock:powermock-module-junit4:1.7.0
    • org.powermock:powermock-api-mockito2:1.7.0

更新1:根据您显示测试方法的更新问题...

我的示例包括:@PrepareForTest({ResponseMapper.class})您的测试方法准备ResponseMapper而不是准备EnterpriseCustomerVerificationService。这就像你正在准备调用具有静态方法的类而不是准备包含静态方法的类的类。

我强烈建议创建一个新的测试用例 - 暂时 - 看起来像我提供的那个,并用它来向自己展示如何模拟一个静态方法,一旦你对它感到满意,然后将其工作到你的{{ 1}}。

答案 1 :(得分:0)

是否可以更改源代码?如果是这样,也许你可以尝试解决问题而不使用任何模拟框架。

查看我对How To Java Unit Test a Complex Class

的评论