【问题标题】:How can I mock the private method inside the method如何在方法中模拟私有方法
【发布时间】:2021-09-20 06:43:08
【问题描述】:

我想为以下代码编写 mockito,但不知道如何为方法 buildGetSubtenantsURL 、getSubtenants、getSubtenantName 中的方法编写 -

 public void addNewMap(MapDTO mapDTO) {
            `...............................`
            String subtenantsURL = buildGetSubtenantsURL(null); 
            String subTenantsResponse  = getSubtenants(subtenantsURL,iottenant);
            JSONObject subTenant = getSubtenantName(subTenantsResponse);
            checkForMultiplePagesSubtenants(subTenantsResponse, subtenantInfoMap,iottenant);
            
            if(subtenantInfoMap.get(mapDTO.getSubtenantName()) != null) {
                mapEntity = Maps.builder().subtenant(subtenantInfoMap.get(mapDTO.getSubtenantName()).toString()).build();
            }
            else {
                throw new DataNotFoundException(SUBTENANT_DOESNT_EXIST);
            }
            
            String SubtenantId = subtenantInfoMap.get(mapDTO.getSubtenantName());
            UriComponents assetsURL = buildGetAssetsURL(iottenant,SubtenantId);
            String assetsResponse = getAssets(assetsURL, iottenant);
            String mindsphereAssetId = getAssetId(assetsResponse);
        }

String url = new StringBuilder().append(mindsphereBaseURL).append(mindsphereAssetsURL).toString();
    UriComponents baseUriComponents = UriComponentsBuilder.fromHttpUrl(url).build();
    JSONObject typeId = new JSONObject();
    typeId.put(Constants.TYPEID, iottenant + "." + assetType);
    typeId.put(Constants.SUBTENANT,SubtenantId);
    baseUriComponents = UriComponentsBuilder.fromUri(baseUriComponents.toUri())
            .queryParam(Constants.FILTER, typeId.toString()).queryParam(Constants.BASIC_FIELDS_ONLY,"true").build().encode();

    return baseUriComponents;

【问题讨论】:

    标签: java spring-boot mockito spring-test powermockito


    【解决方案1】:

    您无法使用 Mockito 实现这一目标。为此,您需要 Powermock(查看https://www.baeldung.com/powermock-private-method 了解详细信息和示例)。

    话虽如此,模拟私有方法是一种非常糟糕的做法。通过这样做,您将测试什么?这将是部分单元测试(因为您甚至没有测试整个单元,即被测类)?我的建议是尽可能避免这种情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 1970-01-01
      • 2017-03-15
      • 1970-01-01
      相关资源
      最近更新 更多