Home > Mobile >  How can I mock the private method inside the method
How can I mock the private method inside the method

Time:09-21

I want to write mockito for the following code , but not getting how to write for method inside method 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;

CodePudding user response:

You can't achieve this with Mockito. For that, you would need Powermock (check https://www.baeldung.com/powermock-private-method for details and examples).

Having said that, mocking private methods is a really bad practice. By doing so what will you be testing? Will this be a partial unit test (since you are not even testing the whole unit, which is the class under test)? My suggestion is that you avoid this as harder as you can.

  • Related