function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SFDCDevQASFDCDevQA 

Test class not asserting properly - despite manual testing working perfectly

I have a Class that is working perfectly in real life (as in be a user and go through the steps and everything works fine) but my test class keeps failing because somehow it is getting more than the one line that it should be for Chosen Contacts at the beginning.  It's actually getting more than 2 chosen contacts which is more contacts than even exist so the whole thing doesn't make sense. I can't figure out why.   If someone could please take a peak and see what could be causing this issue that would be wonderful.  I've been spinning for over a week.  I have another class and test class that is almost exactly the same and it works just fine but this one is doing strange things for some reason I can't figure out.  I know a user in real life has no problems but the test is somehow creating indefinite starting records or something.

 

Thanks,

Amanda

 

Class

public with sharing class QuoteContactEntryExtension {

    public Quote theQuote {get;set;} { theQuote = new Quote(); }
    public String searchString {get;set;}
    public Quote_Contact__c[] chosencontacts {get;set;} { chosencontacts = new List<Quote_Contact__c>(); }
    public OpportunityContactRole[] availablecontacts {get;set;} { availableContacts = new List<OpportunityContactRole>(); }
    public Opportunity theOpp {get;set;} { theOpp = new Opportunity();}
    
    public String toSelect {get; set;}
    public String toUnselect {get; set;}
    public Decimal Total {get;set;}
    
    public Boolean overLimit {get;set;}
    
    private Quote_Contact__c[] forDeletion = new Quote_Contact__c[]{};


    public QuoteContactEntryExtension(ApexPages.StandardsetController controller) {

        Id QuoteID = ApexPages.currentPage().getParameters().get('id');

        // Get information about the Quote being worked on
        theQuote = [select Id, OpportunityID, Opportunity.Name from Quote where Id = :QuoteID limit 1];
       
        
        // If demo contacts were previously selected need to put them in the "selected contacts" section to start with
        chosencontacts = [
            select Id, Contact__c, Adoption_Agreement__c
            from Quote_Contact__c
            where Adoption_Agreement__c = :QuoteID
        ];
        
        theopp = thequote.opportunity;

        updateAvailableList();

    }
    
    // this is the 'action' method on the page
    public PageReference OpportunityCheck(){
        //if there is only one Opportunity we go with it and save the opp
            if(theQuote.OpportunityId != theopp.id){
                try{
                    theQuote.OpportunityId = theopp.id;
                    update(theQuote);
                }
                catch(Exception e){
                    ApexPages.addMessages(e);
                }
            }
            
            return null;
    
    }
       
    
    public void updateAvailableList() {
        
        // We dynamically build a query string and exclude items already in the shopping cart
        String qString = 'select Id, ContactId, OpportunityId from OpportunityContactRole where OpportunityId = \'' + theOpp.Id + '\'';
                
        // note that we are looking for the search string entered by the user in the First Name OR Last Name
        // modify this to search other fields if desired
        if(searchString!=null){
            qString+= ' and (OpportunityContactRole.Contact.FirstName like \'%' + searchString + '%\' or OpportunityContactRole.Contact.LastName like \'%' + searchString + '%\')';
        }
        
        Set<Id> selectedEntries = new Set<Id>();
        for(Quote_Contact__c d:chosencontacts){
            selectedEntries.add(d.contact__c);
        }
        
        if(selectedEntries.size()>0){
            qString += ' and ContactId not in :selectedEntries';
/*
            String tempFilter = ' and Id not in (';
            for(Id i : selectedEntries){
                tempFilter+= '\'' + (String)i + '\',';
            }
            String extraFilter = tempFilter.substring(0,tempFilter.length()-1);
            extraFilter+= ')';
            
            qString+= extraFilter;*/
        }
        
        qString+= ' order by OpportunityContactRole.Contact.Name';
        qString+= ' limit 101';
        
        system.debug('qString:' +qString);        
        availablecontacts = database.query(qString);
        
        // We only display up to 100 results... if there are more than we let the user know (see vf page)
        if(availablecontacts.size()==101){
            availablecontacts.remove(100);
            overLimit = true;
        }
        else{
            overLimit=false;
        }
    }
    
    public void addTochosencontacts(){
    
        // This function runs when a user hits "select" button next to a contact
    
        for(opportunitycontactrole d : availablecontacts){
            if((String)d.Id==toSelect){
                chosencontacts.add(new Quote_Contact__c(Adoption_Agreement__c=theQuote.Id, contact__c=d.contactid));
                break;
            }
        }
        
        updateAvailableList();  
    }
    

    public PageReference removeFromchosencontacts(){
    
        // This function runs when a user hits "remove" on an item in the "Chosen Contacts" section
    
        Integer count = 0;
    
        for(Quote_Contact__c d : chosencontacts){
            if((String)d.contact__c==toUnselect){
            
                if(d.Id!=null)
                    forDeletion.add(d);
            
                chosencontacts.remove(count);
                break;
            }
            count++;
        }
        
        updateAvailableList();
        
        return null;
    }

    public PageReference onSave(){
    
        // If previously selected contacts are now removed, we need to delete them
        if(forDeletion.size()>0)
            delete(forDeletion);
    
        // Previously selected contacts may have new information, so we use upsert here
 try{
      if (chosencontacts.size() > 0)        
          upsert(chosencontacts);
       }
        catch(Exception e){
            ApexPages.addMessages(e);
            return null;
        }
             
        // After save return the user to the Quote
        return new PageReference('/' + ApexPages.currentPage().getParameters().get('Id'));
    }
    
    public PageReference onCancel(){
 
        // If user hits cancel we commit no changes and return them to the Quote   
        return new PageReference('/' + ApexPages.currentPage().getParameters().get('Id'));
    }
    
 
}

 

 

 

Test Class

@istest
private class TestQuoteContactEntryExtension{

static testMethod void theTests(){

{

//Create Test Data

Account a=new Account(Name='Test Account');
    insert a;
Contact c = new Contact(FirstName='John',LastName='Doe', AccountID=a.id);
    insert c;
Contact c2 = new Contact(FirstName='Jane',Lastname='Doe',AccountID=a.id);
    insert c2;
Opportunity o = new Opportunity(Name='Test Opportunity',Academic_Term__c='Spring',closedate=system.today(), stagename='Confirmed Teaching/Class Schedule',Probability=0.05, accountID=a.id);
    insert o;      
OpportunityContactRole ocr = new OpportunityContactRole (Opportunityid = o.id, Contactid=c.id, role='Decision Maker', isPrimary=True) ;     
    insert ocr;  
OpportunityContactRole ocr2 = new OpportunityContactRole (Opportunityid = o.id, Contactid=c2.id, role='Decision Maker', isPrimary=False) ;     
    insert ocr2;  
Quote q = new Quote (Name='Test Demo', Opportunityid=o.id);
    insert q;
Quote_Contact__c qcc = new Quote_Contact__c (Adoption_Agreement__c=q.id, contact__c=c.id);
    insert qcc;

     
        ////////////////////////////////////////
        //  test QuoteContactEntry
        ////////////////////////////////////////
        
// load the page       
        PageReference pageRef = Page.Quote_Contact_Entry;
        pageRef.getParameters().put('Id',qcc.Adoption_Agreement__c);
        Test.setCurrentPageReference(pageRef);
        
 List<Quote> quotes = new List<quote>();
    quotes.add( [ Select Id, Opportunityid From Quote Where Id = : qcc.Adoption_Agreement__c ] );       
        
        QuoteContactEntryExtension qCEE = new QuoteContactEntryExtension(new ApexPages.StandardSetController( quotes ));
        

        // we know that there is at least one line item, so we confirm
        Integer startCount = qCEE.chosencontacts.size();
        system.assert(startCount>0);

        //test search functionality without finding anything
        qCEE.searchString = 'michaelforce is a hip cat';
        qCEE.updateAvailableList();
        system.assert(qCEE.availablecontacts.size()==0);
        
        //test remove from shopping cart
        qCEE.toUnselect = qcc.contact__c;
        qCEE.removeFromchosencontacts();
        system.assert(qCEE.chosencontacts.size()==startCount-1);
        
        //test save and reload extension
        qCEE.onSave();
        qCEE = new QuoteContactEntryExtension(new ApexPages.StandardSetController(quotes));
        system.assert(qCEE.chosencontacts.size()==startCount-1);
        
        // test search again, this time we will find something
        qCEE.searchString = qcc.Contact__r.FirstName;
        qCEE.updateAvailableList();
        system.assert(qCEE.availablecontacts.size()>0);       

        // test add to Shopping Cart function
       qCEE.toSelect = qCEE.availablecontacts[0].Id;
       qCEE.addTochosencontacts();
       system.assert(qCEE.chosencontacts.size()==startCount);
                
        // test save method
        
        qCEE.onSave();
        
        // query line items to confirm that the save worked
        Quote_Contact__c[] qcc2 = [select Id from Quote_Contact__c where Adoption_Agreement__c = :qcc.Adoption_Agreement__c];
       system.assert(qcc2.size()==startCount);
        
        // test on new quote to make sure redirect is happening
        Quote newQuote = new Quote(Name='New Quote2', Opportunityid= o.id);
        insert(newQuote);
        qCEE = new QuoteContactEntryExtension(new ApexPages.StandardSetController(quotes));
        
        // final quick check of cancel button
        System.assert(qCEE.onCancel()!=null);
        
        
        ////////////////////////////////////////
        //  test redirect page
        ////////////////////////////////////////
        
        // load the page
        pageRef = Page.QuoteContactRedirect;
        pageRef.getParameters().put('Id',qcc2[0].Id);
        Test.setCurrentPageReference(pageRef);

        // load the extension and confirm that redirect function returns something
        QuoteContactRedirectExtension qcrE = new QuoteContactRedirectExtension(new ApexPages.StandardController(qcc2[0]));
        System.assert(qcrE.redirect()!=null);
     
    }
}
}

Best Answer chosen by Admin (Salesforce Developers) 
SFDCDevQASFDCDevQA

Finally figured it out myself.  I didn't think about a trigger on the Quote creating the initial Quote Contacts so I was creating a duplicate Quote Contact in addition to the ones the trigger was creating for me when I inserted the Quote.  Removed my manual creation of a quote contact and changed all it's associations to the specific quote or contact and now it works perfectly.  Yay!