我怎样才能模拟方法内部的私有方法

How can I mock the private method inside the method

我想为以下代码编写 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;

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

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