1

I am having difficulties writing a test class for two of my classes. One is a webservice class and the other is a helper class. I have those two working in my code just fine, but am absolutely lost as i'm trying to write the test class for both of those classes. Any help would be greatly appreciated. Thanks so much.

THIS IS THE WEBSERVICE CLASS:

global class Oppty_Search_IntegrationOperation {
    //Opportunity search data from AIC
    global class Oppty_SearchData{
        webservice String opptyName;
        webservice String opptyNo;
        //Modified xxxxPartyNo to be type Integer to align with UCID in federal
        webservice String soldToPartyNo;//Distributor/Direct Reseller party_number__c
        webservice String endCustPartyNo;//Account.Party_number__c
        webservice String tier2PartyNo;//Distribution_VAR__r.Party_number__c
        webservice String distributionChannel;//Sales_Channel__c
        webservice String primarySalesRep;//BadgeID of Salesrep
        webservice String hybrisUser;//BadgeID of user logged into Hybris
    }

    // Opportunity Search result class
    global class Oppty_SearchResponse{
        webservice Boolean isSuccess {set;get;}
        webservice String errorMessage {set;get;}
        webservice List<OpptyWrapper> lstOppWrapResults {set;get;}
    }
    //Opportunity wrapper class to send AIC
    global class OpptyWrapper {
        webservice String name;
        webservice String opptyNumber;
        webservice String stageName;
        webservice Double amount; 
        webservice String distributionChannel;
        webservice Date   closeDate;
        webservice String accountName;
        webservice String tier2Partner;  
    }

    //Main web-service method
    webservice static Oppty_SearchResponse performOpptySearch(Oppty_SearchData opptySearchData){
    List<OpptyWrapper> lstOpptyWraper = new List<OpptyWrapper>();
        Oppty_SearchHelper_IntegrationOperation searchHelper = new Oppty_SearchHelper_IntegrationOperation();
        Oppty_SearchResponse opptySearchResponse = new Oppty_SearchResponse();
        try{// Perform search operation
            opptySearchResponse= searchHelper.performOpptyHelperSearch(opptySearchData);
        }catch(Exception e){//On any error set operation is unsuccessful and send error message back
            opptySearchResponse.isSuccess= false;
            opptySearchResponse.errorMessage = 'Exception in Main class :getStackTraceString : ' + e.getStackTraceString() + ' -  Cause : ' + e.getCause() + ' - LineNumber : ' + e.getLineNumber() + ' - Message : ' + e.getMessage();
        }
    return opptySearchResponse;
    }
}

THIS IS THE HELPER CLASS:

public class Oppty_SearchHelper_IntegrationOperation {
    public static Oppty_Search_IntegrationOperation.Oppty_SearchData searchData = null;
    public static Oppty_Search_IntegrationOperation.Oppty_SearchResponse staticSearchResponse = null;
    public static String exceptionDescription = null;
    static Boolean isSOSL = false;
    //Method to perform all search functionalities 
    public Oppty_Search_IntegrationOperation.Oppty_SearchResponse performOpptyHelperSearch(Oppty_Search_IntegrationOperation.Oppty_SearchData sData){
       searchData = sData;
        String query= null;
        staticSearchResponse = new Oppty_Search_IntegrationOperation.Oppty_SearchResponse();
        try{
            query = prepareQuery(searchData);//Prepare & get query based on criteria
            staticSearchResponse = performSearch(query, searchData);//Perform Oppty search and do salesRep access validation then get list of Opptys
        }catch(Exception e){
            if(exceptionDescription!=null){
                staticSearchResponse.errorMessage = exceptionDescription;
            }else {
                staticSearchResponse.errorMessage = 'Exception : ' + e.getMessage();
            }
            staticSearchResponse.isSuccess = false;
        }
        System.debug('**** final response = '+ staticSearchResponse);
        return staticSearchResponse;
    }

    //Method to construct SOQL query based of search criteria.
    private String prepareQuery(Oppty_Search_IntegrationOperation.Oppty_SearchData searcData){
        System.debug('**** in query Method');
        String query;
        String queryWHERE= 'WHERE';
        String fullQuary;

        query = 'SELECT  Name, Opportunity_Number__c,StageName,Amount,Sales_Channel__c,CloseDate,Account.Name,Distribution_VAR__r.Name FROM Opportunity ';

        if((searcData.distributionChannel ==null || searcData.distributionChannel =='') || (searcData.primarySalesRep  ==null || searcData.primarySalesRep  =='')){
            staticSearchResponse.isSuccess=false;

            if(searcData.distributionChannel ==null || searcData.distributionChannel =='')//distributionChannel is mandatory
                exceptionDescription = 'Mandatory field Distribution Channel not found';

            if(searcData.primarySalesRep  ==null || searcData.primarySalesRep  =='')//primarySalesRep is mandatory
                exceptionDescription = 'Mandatory field Sales Rep not found';

            throw new SearchException('############### Exception : One or more mandatory field values not found...');
        }else if(searcData.opptyNo==null || searcData.opptyNo==''){//If opptyNo is provided, then soldToPartyNo or endCustPartyNo is no longer mandatory
            System.debug('*** opptyNo not found ');
            staticSearchResponse.isSuccess=false;
                if((searcData.soldToPartyNo ==null || searcData.soldToPartyNo =='') || (searcData.endCustPartyNo  ==null || searcData.endCustPartyNo  =='')){
                    if(searcData.soldToPartyNo ==null || searcData.soldToPartyNo =='')//soldToPartyNo is mandatory if opptyNo is not provided
                        exceptionDescription = 'Mandatory field Sold To Party Number not found';

                    if(searcData.endCustPartyNo  ==null || searcData.endCustPartyNo  =='')//endCustPartyNo is mandatory if opptyNo is not provided
                        exceptionDescription = 'Mandatory field End Customer Party Number not found';
                    throw new SearchException('############### Exception : One or more mandatory field values not found...');
                }
            }
        System.debug('*** After Exceptions');
         String searchSOSLQuery;

        //Create Custom setting to check is distribution channel is 'Indirect'
        Propel_General_Settings__c propelSettings = Propel_General_Settings__c.getInstance();
        Set<String> setValues = new Set<String>(propelSettings.Indirect_Distribution_Channels__c.split(';'));

        //Add critieria for Oppoprtunity Number
       if(searcData.opptyNo!=null && searcData.opptyNo!=''){
            if(!queryWHERE.endsWith('WHERE')) 
                    queryWHERE += ' AND';
                queryWHERE+=' Opportunity_Number__c=\'' + String.escapeSingleQuotes(searcData.opptyNo) +'\'';
                System.debug('*** added Opportunity_Number__c to query ' + searcData.opptyNo);

                if (setValues==null || setValues.isEmpty()){
                exceptionDescription ='Please difine CutomSetting for distribution channel';
                System.debug('#### Exception on getting CutomSetting for distribution channel ');
                throw new SearchException('#### Exception on getting CutomSetting for distribution channel ');
            }
            System.debug('**** setValues.contains(searcData.distributionChannel) = ' + setValues.contains(searcData.distributionChannel));
            if(searcData.distributionChannel !=null && setValues.contains(searcData.distributionChannel)){
            System.debug('**** in side distributionChannel not null');
                if(searcData.soldToPartyNo!= null && searcData.soldToPartyNo != ''){
                System.debug('**** soldToPartyNo is not empty ');
                    if(!queryWHERE.endsWith('WHERE'))
                    queryWHERE += ' AND';
                    queryWHERE +=' (Direct_Reseller_Distributor__r.UCID__c = \'' + searcData.soldToPartyNo + '\')';//??? PENDING : EXCEPTION ON RELATION
                    System.debug('*** added Sales_Channel__c to query ' + searcData.distributionChannel);
                    System.debug('*** added Disti/Direct Reseller to query ' + searcData.soldToPartyNo );
                    System.debug('*** LINE 103 - query to this point ' + queryWHERE );
                }
                if(searcData.tier2PartyNo != null && searcData.tier2PartyNo != ''){
                    if(!queryWHERE.endsWith('WHERE'))
                    queryWHERE += ' AND';
                    queryWHERE +=' Distribution_VAR__r.UCID__c= \'' + searcData.tier2PartyNo + '\'';
                }           
            }
        }   
        else {
            if(searcData.opptyName!=null && searcData.opptyName!='') {
                if(!queryWHERE.endsWith('WHERE'))
                        queryWHERE += ' AND';
                        isSOSL = true;
                        System.debug('**** in opp name condition');
                         searchSOSLQuery = 'FIND \''+ String.escapeSingleQuotes(searcData.opptyName) +'*\' IN NAME FIELDS RETURNING Opportunity(Name, Opportunity_Number__c,StageName,Amount,Sales_Channel__c,CloseDate,Account.Name,Distribution_VAR__r.Name '; 
               System.debug('*** adding name to query');
            }

            List<Account> endCustomer= null;
            endCustomer = [SELECT Name, Account_District__c, Site_DUNS_Entity__c FROM Account WHERE UCID__c=:searcData.endCustPartyNo];

            if(endCustomer ==null || endCustomer.isEmpty()){
                exceptionDescription = 'End Customer Not Found';
                throw new SearchException('############### Exception : End Customer not found...');
            } else {
            //System.debug('***searcData.endCustPartyNo =  '+ searcData.endCustPartyNo + ' : endCustomer size = ' + endCustomer.size());
                //System.debug('*** endCustomer District_Lookup__c = ' + endCustomer[0].District_Lookup__c   +'  %%%%%% Account_District__c = ' + endCustomer[0].Account_District__c);

                if(endCustomer[0].Site_DUNS_Entity__c != null && endCustomer[0].Account_District__c != null){
                    if(!queryWHERE.endsWith('WHERE'))
                            queryWHERE += ' AND';
                    queryWHERE +=' account.Site_DUNS_Entity__c=\'' + String.escapeSingleQuotes(endCustomer[0].Site_DUNS_Entity__c) +'\'';
                    queryWHERE +=' AND account.Account_District__c=\'' + String.escapeSingleQuotes(endCustomer[0].Account_District__c) +'\'';
                    System.debug('*** added account.Site_DUNS_Entity__c to query ' + endCustomer[0].Site_DUNS_Entity__c);
                } else {//Added code as per defect 17005 on Cycle0 testing
                    if(!queryWHERE.endsWith('WHERE'))
                                queryWHERE += ' AND';
                    queryWHERE +=' account.UCID__c = \'' +searcData.endCustPartyNo + '\'';
                    System.debug('*** account.UCID__c ');
                }
            }
             System.debug('**** setValues = ' + setValues + ' : searcData.distributionChannel = ' + searcData.distributionChannel);

            if (setValues==null || setValues.isEmpty()){
                exceptionDescription ='Please difine CutomSetting for distribution channel';
                System.debug('#### Exception on getting CutomSetting for distribution channel ');
                throw new SearchException('#### Exception on getting CutomSetting for distribution channel ');
            }
            System.debug('**** setValues.contains(searcData.distributionChannel) = ' + setValues.contains(searcData.distributionChannel));
            if(searcData.distributionChannel !=null && setValues.contains(searcData.distributionChannel)){
            System.debug('**** in side distributionChannel not null');
                if(searcData.soldToPartyNo!= null && searcData.soldToPartyNo != ''){
                System.debug('**** soldToPartyNo is not empty ');
                    if(!queryWHERE.endsWith('WHERE'))
                    queryWHERE += ' AND';
                    queryWHERE +=' (Direct_Reseller_Distributor__r.UCID__c = \'' + searcData.soldToPartyNo + '\')';
                    System.debug('*** added Sales_Channel__c to query ' + searcData.distributionChannel);
                    System.debug('*** LINE ~182 - query to this point ' + queryWHERE );
                }
                if(searcData.tier2PartyNo != null && searcData.tier2PartyNo !=''){
                    if(!queryWHERE.endsWith('WHERE'))
                    queryWHERE += ' AND';
                    queryWHERE +=' Distribution_VAR__r.UCID__c= ' + searcData.tier2PartyNo + '\'';
                }           
            }
        }//else - end

        if(!queryWHERE.endsWith('WHERE')) 
                    queryWHERE += ' AND';
        queryWHERE += ' (Forecast_Category__c IN(\'Pipeline\',\'Strong Upside\', \'Upside\',\'Won\', \'Commit\'))';

        //Add ORDER BY clouse to query
        queryWHERE += ' ORDER BY name';

        //add limit to query to 200
        queryWHERE +=' LIMIT 100';


        if(isSOSL){
            fullQuary = searchSOSLQuery + queryWHERE + ')';
        } else{
            fullQuary = query + queryWHERE;
        }
        System.debug('*** before returning fullQuary = ' + fullQuary);
        return fullQuary;
    }
    //Method to query the opportunities and filter according to sales rep access
    private Oppty_Search_IntegrationOperation.Oppty_SearchResponse performSearch(String query, Oppty_Search_IntegrationOperation.Oppty_SearchData searData){
       System.debug('*** start performSearch method');
        Oppty_Search_IntegrationOperation.Oppty_SearchResponse searchResponse1 = new Oppty_Search_IntegrationOperation.Oppty_SearchResponse();
        //staticSearchResponse = new Oppty_Search_IntegrationOperation.Oppty_SearchResponse();
        List<Opportunity> lisOppty = null;
        List<Opportunity> lisResultOpptys = null;
        Map<Id,Opportunity> mapResultSalesRepOpptys = new Map<Id, Opportunity>();
        Map<Id,Opportunity> mapResultUserOpptys = new Map<Id, Opportunity>();
        boolean noSalesRepAccess = false;
        boolean noUserAccess = false;
     //try{
        try{
            if(isSOSL){
                    List<List<SObject>> objects = search.query(query);
                    lisOppty = (List<Opportunity>)objects[0];
                    System.debug('**** objects = ' + objects);
                    System.debug('***** SOSL returned Opptyels = ' + lisOppty);
            } else {
                 lisOppty = Database.query(query);
            }           
            System.debug('**** Qeury execution success lisOppty = ' + lisOppty);
        }catch(Exception e){
            exceptionDescription = 'Exception on searching for Opportunity';
            System.debug('############ Exception : on querying : ' + e.getMessage());
            throw new SearchException('Exception on searching for Opportunity');
        }
        //if no opportunities are found set isSuccess false and return
        if(lisOppty.isEmpty()){
            exceptionDescription = 'No matching Opportunities found for this Search Criteria';
            System.debug('**** Query not returned any record');
            throw new SearchException('No matching Opportunities found for this Search Criteria');
        } else {//if found some opptys
            System.debug('**** found records size = ' + lisOppty.size());
            System.debug('**** found lisOppty = ' + lisOppty);

            //Filter Oppty records according to sales rep access
            mapResultSalesRepOpptys = filterSalesRepOpptys(lisOppty,searData);
            mapResultUserOpptys = filterUserOpptys(lisOppty,searData);
            if((mapResultSalesRepOpptys== null || mapResultSalesRepOpptys.isEmpty()) || (mapResultUserOpptys== null || mapResultUserOpptys.isEmpty())){
                if((mapResultSalesRepOpptys== null || mapResultSalesRepOpptys.isEmpty()) && (mapResultUserOpptys== null || mapResultUserOpptys.isEmpty())){
                    exceptionDescription = 'No matching Opportunities found with this Sales Rep or User access for this Search Criteria';
                    throw new SearchException('No matching Opportunities found with this Sales Rep or User access for this Search Criteria');    
                } else if((mapResultSalesRepOpptys== null || mapResultSalesRepOpptys.isEmpty())){
                    exceptionDescription = 'No matching Opportunities found with this Sales Rep access for this Search Criteria';
                    throw new SearchException('No matching Opportunities found with this Sales Rep access for this Search Criteria');
                } else {
                    exceptionDescription = 'No matching Opportunities found with this User access for this Search Criteria';
                    throw new SearchException('No matching Opportunities found with this User access for this Search Criteria');
                }
            }

            lisResultOpptys = new List<Opportunity>();

            if((mapResultSalesRepOpptys != null && !mapResultSalesRepOpptys.isEmpty()) && (mapResultUserOpptys != null && !mapResultUserOpptys.isEmpty())){
                for(Opportunity ResultUserOppt : mapResultUserOpptys.values()){
                    System.debug('***** ResultUserOppt = ' + ResultUserOppt);
                    System.debug('***** ResultUserOpptID = ' + ResultUserOppt.Id);
                    if(mapResultSalesRepOpptys.containsKey(ResultUserOppt.Id)){
                        System.debug('***** is in both lists');
                        System.debug('***** lisResultOpptys before = ' + lisResultOpptys);
                        lisResultOpptys.add(ResultUserOppt);
                        System.debug('***** lisResultOpptys after = ' + lisResultOpptys);
                    }
                }
            }

            //lisResultOpptys = filterSalesRepOpptys(lisOppty,searData);
            System.debug('*** alfer filter lisResultOpptys.size() = ' + lisResultOpptys.size());
        }
        List<Oppty_Search_IntegrationOperation.OpptyWrapper> lstOpptyWraper = new List<Oppty_Search_IntegrationOperation.OpptyWrapper>();
        //Create OpptyWrapper object from final result of list of Opptys to send back
        if(lisResultOpptys != null && !lisResultOpptys.isEmpty()){
            Oppty_Search_IntegrationOperation.OpptyWrapper oppWrap = null;
            for(Opportunity oppty : lisResultOpptys){
                oppWrap = new Oppty_Search_IntegrationOperation.OpptyWrapper();
                oppWrap.name = oppty.Name;
                oppWrap.opptyNumber = oppty.Opportunity_Number__c;
                oppWrap.stageName = oppty.StageName;
                oppWrap.amount = oppty.Amount; 
                oppWrap.distributionChannel = oppty.Sales_Channel__c;
                oppWrap.closeDate = oppty.CloseDate;
                oppWrap.accountName = oppty.Account.Name;
                oppWrap.tier2Partner = oppty.Distribution_VAR__r.Name;
                lstOpptyWraper.add(oppWrap);
            }   
        }
        if (lstOpptyWraper != null && !lstOpptyWraper.isEmpty()){
            searchResponse1.isSuccess=true; 
            searchResponse1.lstOppWrapResults = lstOpptyWraper;
            System.debug('*** returning response searchResponse1 = ' + searchResponse1);
            System.debug('*** searchResponse1.lstOppWrapResults = ' + searchResponse1.lstOppWrapResults);
        } else {
            System.debug('**** lstOpptyWraper is null ');
        }
        return searchResponse1;
    }
    //Method to filter opportunities based on SalesRep access
    private Map<Id, Opportunity> filterSalesRepOpptys(List<Opportunity> lstOptyToFilter,Oppty_Search_IntegrationOperation.Oppty_SearchData seaData){
        Map<Id,Opportunity> mapOfOptys = new Map<Id,Opportunity>(lstOptyToFilter);

        Set<Id> setUnSortedOpptysIds = new Set<Id>();
        Map<Id, Opportunity> mapFilteredOpptys = new Map<Id, Opportunity>();
        List<Opportunity> limitedOpptys = new List<Opportunity>();
        List<User> salseRepbadgeID= null;
            salseRepbadgeID = [SELECT Id FROM User WHERE IsActive=true and FederationIdentifier =:seaData.primarySalesRep limit 1];

        Id srid = salseRepbadgeID[0].Id;

        Map<Id,UserRecordAccess> mapURA = new Map<Id,UserRecordAccess>([SELECT RecordId FROM UserRecordAccess WHERE HasReadAccess = true AND UserId =:srid AND RecordId=:mapOfOptys.keyset()]);

        Integer count= 0;

        for(UserRecordAccess ura : mapURA.values()){
            setUnSortedOpptysIds.add(ura.RecordId);
        }

         //Sort the Opportunities on order
        if(mapURA!=null && mapURA.size()>0){
                for(Opportunity opp : lstOptyToFilter){
                    if(setUnSortedOpptysIds.contains(opp.Id)){
                        //lstfilteredOpptys.add(opp);
                        mapFilteredOpptys.put(opp.id, opp);
                        System.debug('*** Adding to mapFilteredOpptys mapOfOptys.get(oppId).Name = ' + opp.Name);
                        count++;
                    if(count==50){
                        break;
                    }
                    }
                }
        }
        //return all list of opportunities
        System.debug('*** Sending all Opptyes mapFilteredOpptys.values() = ' + mapFilteredOpptys);
        return mapFilteredOpptys;
    }

    private Map<Id,Opportunity> filterUserOpptys(List<Opportunity> lstOptyToFilter2,Oppty_Search_IntegrationOperation.Oppty_SearchData seaData){
        Map<Id,Opportunity> mapOfOptys2 = new Map<Id,Opportunity>(lstOptyToFilter2);

        Set<Id> setUnSortedOpptysIds2 = new Set<Id>();
        Map<Id, Opportunity> mapFilteredOpptys2 = new Map<Id, Opportunity>();
        List<Opportunity> limitedOpptys2 = new List<Opportunity>();
        List<User> userBadgeID= null;
            userBadgeID = [SELECT Id FROM User WHERE IsActive=true and FederationIdentifier =:seaData.hybrisUser limit 1];

        Id uid = userBadgeID[0].Id;

        Map<Id,UserRecordAccess> mapURA2 = new Map<Id,UserRecordAccess>([SELECT RecordId FROM UserRecordAccess WHERE HasReadAccess = true AND UserId =:uid AND RecordId=:mapOfOptys2.keyset()]);

        Integer count2= 0;

        for(UserRecordAccess ura2 : mapURA2.values()){
            setUnSortedOpptysIds2.add(ura2.RecordId);
        }

         //Sort the Opportunities on order
        if(mapURA2!=null && mapURA2.size()>0){
                for(Opportunity opp2 : lstOptyToFilter2){
                    if(setUnSortedOpptysIds2.contains(opp2.Id)){
                        //lstfilteredOpptys.add(opp);
                        mapFilteredOpptys2.put(opp2.id, opp2);
                        System.debug('*** Adding to mapFilteredOpptys2 mapOfOptys2.get(oppId).Name = ' + opp2.Name);
                        count2++;
                    if(count2==50){
                        break;
                    }
                    }
                }
        }
        //return all list of opportunities
        System.debug('*** Sending all Opptyes mapFilteredOpptys2.values() = ' + mapFilteredOpptys2);
        return mapFilteredOpptys2;
    }

    public class SearchException extends Exception {}
}

HERE IS WHAT I CURRENTLY HAVE AS MY TEST CLASS:

@isTest
private class OpportunitySearch_Test{
  static testMethod void OpportunitySearch_Test_Svc()
  {
      Oppty_Search_IntegrationOperation.Oppty_SearchData opptySearchData = new Oppty_Search_IntegrationOperation.Oppty_SearchData();
      opptySearchData.opptyName= 'test';
      opptySearchData.opptyNo = '123';
      opptySearchData.soldToPartyNo = '1234';
      opptySearchData.endCustPartyNo = '1232';
      opptySearchData.tier2PartyNo = '123';
      opptySearchData.distributionChannel = 'Direct';
      Oppty_Search_IntegrationOperation.performOpptySearch( opptySearchData);

      List<Opportunity> oSR = [select Name from Opportunity where Name = 'test'];
      System.assertEquals(oSR.size(), 0);


    //Insert Account records
    List<Account> accList = new List<Account>();
    accList.add(new Account(Name = 'TestAcount0',Party_Number__c='111',ShippingCountry = 'United States'));
    accList.add(new Account(Name = 'TestAcount1',Party_Number__c= '222',ShippingCountry = 'United States'));
    accList.add(new Account(Name = 'TestAcount3',Party_Number__c= '333',ShippingCountry = 'United States'));
    accList.add(new Account(Name = 'TestAcount4',Party_Number__c= '444',ShippingCountry = 'United States'));
    insert accList;


    //Insert Opportunity records
    List<Opportunity> oppList = new List<Opportunity>();
    oppList.add(new Opportunity (Name = 'Test Opportunity ', AccountId = accList[0].id, Sales_Force__c = 'EMC',StageName = 'Pipeline',CloseDate = System.today(),Amount = 500, Opportunity_Number__c = '9999999',Quote_Cart_Number__c = '1000'));
    oppList.add(new Opportunity (Name = 'Test Opportunity 1', AccountId = accList[1].id, Sales_Force__c = 'EMC',StageName = 'Pipeline',CloseDate = System.today(),Amount = 600, Opportunity_Number__c = '8888888',Quote_Cart_Number__c = '1000'));
    oppList.add(new Opportunity (Name = 'Test Opportunity 2', AccountId = accList[2].id, Sales_Force__c = 'EMC',StageName = 'Pipeline',CloseDate = System.today(),Amount = 700, Opportunity_Number__c = '7777777'));
    oppList.add(new Opportunity (Name = 'Test Opportunity 3', AccountId = accList[3].id, Sales_Force__c = 'EMC',StageName = 'Pipeline',CloseDate = System.today(),Amount = 800, Opportunity_Number__c = '6666666',Quote_Cart_Number__c = '3000'));

    insert oppList;
    List<Opportunity> oppListQueried = new List<Opportunity>();
     oppListQueried = [ Select Id,Name,AccountId,Sales_Force__c,StageName,Amount,Opportunity_Number__c,Quote_Cart_Number__c from Opportunity order by Name];


    Oppty_Search_IntegrationOperation.Oppty_SearchResponse sr = new Oppty_Search_IntegrationOperation.Oppty_SearchResponse();
    sr = Oppty_Search_IntegrationOperation.performOpptySearch(opptySearchData);
}

2 Answers 2

2

Assuming you wrote the code you're trying to test, I'd expect you'd know how to write the rest of the test class once you got started if I pointed you to the following: You'll likely need to begin with a setMock(interfaceType, instance) and invokeContinuationMethod(controller, request) test methods to set up mock responses for your web services. Once you do that, I'd expect you'd be able to work out the rest of the test class on your own. If not, search on the key words and you should find plenty of examples of other test classes that use them.

2

The test code you have already written looks appropriate: your job is to test the logic in your Apex code not the serialization from/to XML that adding the webservice keywords instructs the platform to allow. So calling the code directly is the correct approach.

If your existing test code sets up all the data needed in the logic you are testing, the next step is to add assertions that confirm that the response is as you expect. For the happy path that might be:

 Oppty_Search_IntegrationOperation.Oppty_SearchResponse sr
     = Oppty_Search_IntegrationOperation.performOpptySearch(opptySearchData);
 System.assertEquals(true, sr.isSuccess);
 System.assertEquals(null, sr.errorMessage);
 System.assertEquals(oppListQueried.size(), sr.lstOppWrapResults.size());
 // ... then more asserts to the check content of sr.lstOppWrapResults list

You will probably need several tests to cover the main alternatives (look at the various branches in the code you are testing), and can choose to move the common test setup code out into a static method or inner class to avoid lots of duplicate code. Often the test code ends up being longer than the code your are testing.

On the point about which class to test, I suggest you stick to testing the overall entry point in the Oppty_Search_IntegrationOperation class. That will result in both classes being tested. If you favour "a unit test for every class" as a philosophy, if it is used nowhere else you could merge Oppty_SearchHelper_IntegrationOperation into Oppty_Search_IntegrationOperation; they are very tightly coupled already so having separate classes offers no advantage.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .