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
wcwill978wcwill978 

Help with test class for trigger

Hi I created my first trigger and need help creating a test class (never created one before and dont know how to get started) to get into prod. can someone help me please I tired attaching the trigger, but it gives me anerror saying I exceeded the character limit.

 

Is there a way someone can send me an email please or is there an alternate way for me to post the trigger.

 

 

nasknask

hey u might be having that triiger on some object(Account, contact.. etc any custom object) rite? and on some events (before insert, after insert, ... upadte... etc)rite?

 

So just do the things or cretae a data in such a data that it fires ur trigger. for eg:

if u have triiger

trigger xxxon Account (before insert)

{

 

}

write a test class.

where u just insert ur acc according to ur trriger.

then its done.

wcwill978wcwill978

Yes I have it running on the opportunity. Basically when the opportunity is marked clossed lost or closed won the trigger fires up and creates a new custom object which we call the Win Loss Analysis. The trigger also looks at the Value selected in the Win or Lost Analysis fireld and creates the proper page layout based on record types. I have tested the trigger with multiple opportunities and have done continous test and confirmed it is working correctly and updating the object too if the stage is changed from Won to lost or vise versa. I just need the test class Here is a clip of the trigger:

 

 

trigger AutoCreateWinLossAnalysisOnOpportunityCSL on Opportunity (after update) 
{

    List<Opportunity> closedOps = new List<Opportunity>();
    List<Opportunity> winOps = new List<Opportunity>();
    List<Win_Loss_Analysis__c> newwinLossObjects = new List<Win_Loss_Analysis__c>();    
    List<Win_Loss_Analysis__c> updatewinLossObjects = new List<Win_Loss_Analysis__c>();
    
    List<RecordType> recordTypesForOppty = new List<RecordType>();
    recordTypesForOppty = [Select DeveloperName, ID From RecordType where SobjectType = 'Win_Loss_Analysis__c'];
    List<Id> ExistingIds = new List<Id>();
    
     
    Integer  count = Trigger.new.size(); 
    for(Opportunity newvalue : Trigger.new)
    {
        Opportunity oldvalue = Trigger.oldMap.get(newvalue.Id);
        if(oldvalue.StageName != newvalue.StageName || oldvalue.Loss_Analysis__c != newvalue.Loss_Analysis__c || oldvalue.Win_Analysis__c != newvalue.Win_Analysis__c)  
       {
            if(newvalue.StageName == 'Closed Lost')
            {
                if(newvalue.Loss_Analysis__c == 'Price' 
                    || newvalue.Loss_Analysis__c == 'Product Feature/Functionality' 
                    || newvalue.Loss_Analysis__c =='Relationship')
                {
                   closedOps.add(newvalue);
                   ExistingIds.add(newvalue.Id);
                }
            }
            else if(newvalue.StageName == 'Closed Won')
            {
                if(newvalue.Win_Analysis__c == 'Price' 
                    || newvalue.Win_Analysis__c == 'Service & Support'
                    || newvalue.Win_Analysis__c == 'Product Feature/Functionality'
                    || newvalue.Win_Analysis__c =='Relationship')
                {
                   winOps.add(newvalue);
                   ExistingIds.add(newvalue.Id);
         
                }
            }
       }
       
    }
    system.debug('Found : ' + closedOps.size() + ' Closed Opps that need analysis records created');
    system.debug('Found : ' + winOps.size() + ' Win Opps that need analysis records created');
    if (closedOps.size() > 0 || winOps.size() > 0) 
    
    { 
        List<Win_Loss_Analysis__c> existing = [SELECT Id,Opportunity_Name__c FROM Win_Loss_Analysis__c WHERE  Opportunity_Name__c  in :ExistingIds];
        system.debug('Found : ' + existing.size() + ' Existing Win Loss Records');
        string LossAnalysis = null;
        for (Opportunity oppty : closedOps)
        {           
                    // get the recordTypeId
                    Id WinLossObjectRecordTypeId = null;
                    string typeName;
                    LossAnalysis = oppty.Loss_Analysis__c.toLowerCase();
                    for (RecordType recordType : recordTypesForOppty)
                    {
                        typeName = recordType.DeveloperName.toLowerCase();
                        if (LossAnalysis == 'price' && typeName == 'price') 
                        {
                            WinLossObjectRecordTypeId = recordType.Id;
                        }
                        if (LossAnalysis == 'product feature/functionality' && typeName == 'productfeature') 
                        {
                            WinLossObjectRecordTypeId = recordType.Id;
                        }
                        if (LossAnalysis == 'relationship' && typeName == 'relationship') 
                        {
                            WinLossObjectRecordTypeId = recordType.Id;
                        }
                    }
                    system.debug('Record type id: ' + WinLossObjectRecordTypeId + ' found for oppt id' + WinLossObjectRecordTypeId );
                    // construct the new custom object with the required fields set
                    
                    Win_Loss_Analysis__c wL = new Win_Loss_Analysis__c();
                    wL.Opportunity_Name__c = oppty.Id;
                    wL.RecordTypeId = WinLossObjectRecordTypeId;
                    wL.Account_Name__c = oppty.AccountId;
                    if(existing.size() > 0)
                    {
                        for(Win_Loss_Analysis__c exist : existing)
                        {
                            if(exist.Opportunity_Name__c == oppty.Id)
                            {
                              wL.Id = exist.Id;
                              break;    
                            }                   
                        }
                    }
                    
                    if(wL.Id == null)
                    {
                        newwinLossObjects.add(wL);
                    }
                    else
                    {
                        updatewinLossObjects.add(wL);
                    }
                    
        }
wcwill978wcwill978

Here is the second part of the trigger. this section continues right below the last line on the previous portion I sent in the other post:

 

 

 for (Opportunity oppty : winOps)
        {           
                    // get the recordTypeId
                    Id WinLossObjectRecordTypeId = null;
                    string typeName;
                    string WinAnalysis = oppty.Win_Analysis__c.toLowerCase();
                    for (RecordType recordType : recordTypesForOppty)
                    {
                        typeName = recordType.DeveloperName.toLowerCase();
                         if (WinAnalysis == 'price' && typeName == 'wprice') 
                        {
                            WinLossObjectRecordTypeId = recordType.Id;
                        }
                        if (WinAnalysis == 'product feature/functionality' && typeName == 'wproduct_feature') 
                        {
                            WinLossObjectRecordTypeId = recordType.Id;
                        }
                        if (WinAnalysis == 'service & support' && typeName == 'cust_service') 
                        {
                            WinLossObjectRecordTypeId = recordType.Id;
                        }
                        if (WinAnalysis == 'relationship' && typeName == 'wrelationship') 
                        {
                            WinLossObjectRecordTypeId = recordType.Id;
                        }
                        system.debug('WinAnalysis:' + WinAnalysis + ': typeName:' + typeName + ': WinLossObjectRecordTypeId:' + WinLossObjectRecordTypeId);
                    }
                    system.debug('Record type id: ' + WinLossObjectRecordTypeId + ' found for oppt id' + WinLossObjectRecordTypeId );
                    system.debug('WinAnalysis:' + WinAnalysis + ':' );
                    // construct the new custom object with the required fields set
                    
                    Win_Loss_Analysis__c wL = new Win_Loss_Analysis__c();
                    wL.Opportunity_Name__c = oppty.Id;
                    wL.RecordTypeId = WinLossObjectRecordTypeId;
                    wL.Account_Name__c = oppty.AccountId;
                    if(existing.size() > 0)
                    {
                        for(Win_Loss_Analysis__c exist : existing)
                        {
                            if(exist.Opportunity_Name__c == oppty.Id)
                            {
                              wL.Id = exist.Id;
                              break;    
                            }                   
                        }
                    }
                    
                    if(wL.Id == null)
                    {
                        newwinLossObjects.add(wL);
                    }
                    else
                    {
                        updatewinLossObjects.add(wL);
                    }
                    
        }
    }
    system.debug('Inserting ' + newwinLossObjects.size() + ' new Win Loss Objects' );
    system.debug('Updating ' + updatewinLossObjects.size() + '  Win Loss Objects' );
    if(newwinLossObjects.size() > 0)
        insert newwinLossObjects;
   
    if(updatewinLossObjects.size() > 0)
        update updatewinLossObjects;

}
nasknask

answer is in ur explaination thats it. u need to insert two opp in ur test classs witg one stage = closed lost and other with closed won. ur trigger will be covered.

wcwill978wcwill978

Ok, so how will I write that in a test class. Do I add the test class right into the trigger on top or do I go into Setup --> Develop --> Apex Classes and create a new class. Also how will this class look I've never writen one can you lead me in the right way please.

 

Thank you.

nasknask

i think u r new to write a test class then u better u refer apex PDF there is a hello trigger given and its test class go through that it will help u out with how to wrtie test calss.

bob_buzzardbob_buzzard

There's a really good introduction to triggers on the wiki at:

 

http://wiki.developerforce.com/index.php/An_Introduction_to_Apex_Code_Test_Methods

 

Have a read of that.  You'll need to write a test class that inserts and then updates an opportunity in order to exercise your trigger.  Given that your trigger is quite complex you may need to carry out a number of updates (or inserts followed by updates) to exercise all the paths through your trigger.

Eric.Goehring.ax954Eric.Goehring.ax954

This may get you started;

@isTest
private class TestClass {

    static testMethod void myTestClass() { 
        
        Account a=new Account();
        a.Name='Test Account';
        insert a;
        
        Opportunity o=new Opportunity();
        o.Name='Test Opp1';
        o.StageName='Closed Won';
        o.AccountId=a.Id
        insert o;

        Opportunity o2=new Opportunity();
        o2.Name='Test Opp2';
        o2.StageName='Closed Lost'
        o.AccountId=a.Id
        insert o2;
        }
}