• JN22
  • NEWBIE
  • 485 Points
  • Member since 2012

  • Chatter
    Feed
  • 16
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 100
    Questions
  • 170
    Replies
Hello,

Let me preface this by saying that while I am comfortable coding Apex for Triggers and test classes, I have never coded scheduled Apex and Apex callouts.  I have an external database that I want to bring into SFDC on a nightly basis.  I would like to set up a batch Apex trigger that fires early in the morning and updates either a standard or custom obect with data from the database.  Can anyone point me to resources where I can see sample code on how to accomplish this?  Thanks,
  • August 18, 2014
  • Like
  • 0
Hello,

I have the trigger below set to fire when OpportunityLineItem is updated or inserted.  It's meant to assign a unique number to a custom field called Max_Deliv__c on the OpportunityLineItem object.  The trigger works fine when I add single products, however, when I add multiple products at the same time it assigns the same number to each.  Does anyone know how I can change the trigger to assign a different sequential number to each product added?  Auto number fields will not work because I need the numbering sequence to start over on each new Opportunity.  Thanks,

//Assigns a unique ID to each deliverable in every Opportunity so DyNad can track.
trigger UniqueDelivID on OpportunityLineItem (before insert, before update) {   

if(checkRecursiveBI.runOnceBI()||checkRecursiveBU.runOnceBU())
{
    Set<ID> setOliIds = new Set<ID>();
        for(OpportunityLineItem oli:Trigger.new){
            setOliIds.add(oli.Id);
        }
        Map<ID, OpportunityLineItem> mapOli = new Map<ID, OpportunityLineItem>([SELECT Id, Opportunity.Max_Deliv_Hx__c, Max_Deliv__c
                                                                                FROM OpportunityLineItem
                                                                                WHERE Id in:setOliIds]);
        if(mapOli.size()>0){

/*        List<OpportunityLineItem> oli1 = [SELECT Id, Max_Deliv__c
                                         FROM OpportunityLineItem
                                         WHERE Id IN: Trigger.newMap.keySet()]; 
                                     
            for (OpportunityLineItem oli :oli1){*/
            for(OpportunityLineItem oli1:Trigger.New){
                IF(mapOli.containsKey(oli1.Id) && (oli1.Max_Deliv__c == 0 || oli1.Max_Deliv__c == null)){
                    oli1.Max_Deliv__c = mapOli.get(oli1.Id).Opportunity.Max_Deliv_Hx__c + 1;
                }
            }
        }
}

}


  • July 27, 2014
  • Like
  • 0
Hello,

I am trying to simulate the MAX function on the roll-up summary fields with the trigger below but I am getting an error that my aggregate variable on line 18 is not recognized.  Can any suggest how I can fix this to write the Maximum value of the custom field Max_Deliv__c on my OpportunityLineItem object to the related Opportunity object field Max_Deliv__c?  Thanks,

trigger UpdateMaxDeliv on OpportunityLineItem(before update) {

Set <Id> Opp_Ids = new Set<Id>();
	for (OpportunityLineItem oli1: trigger.new){
		Opp_Ids.add(oli1.Id);
	}

List<AggregateResult> maxDeliv = [SELECT Max(Max_Deliv__c) deliv
								  FROM OpportunityLineItem];
								  
	for(AggregateResult aggOli : maxDeliv);{
 
		List<Opportunity> opp1 = [SELECT Id, Max_Deliv__c
								  FROM Opportunity
								  WHERE Id in :Opp_Ids];

			for(Opportunity o: opp1){
				o.Max_Deliv__c = aggOli.get('deliv');
			}
			update opp1;
		}
}


  • July 26, 2014
  • Like
  • 0
Hello,

I am trying to deploy a trigger (UniqueDelivID) from my sandbox to production.  The trigger works fine in my sandbox and is covered 100% by the test class.  Yet when I try to move to production, I get the error below:

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, OppUpdates: execution of AfterInsert caused by: System.DmlException: Update failed. First exception on row 0 with id 00k7000000U8CVpAAN; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, UniqueDelivID: execution of BeforeUpdate caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.UniqueDelivID: line 22, column 1: [] Trigger.OppUpdates: line 49, column 1: []
Stack Trace: Class.TestOppUpdates.TestOppUpdates: line 379, column 1


Does anyone know why I am getting this error?  Thanks.

Trigger (UniqueDelivID)
//Assigns a unique ID to each deliverable in every Opportunity so DyNad can track.
trigger UniqueDelivID on OpportunityLineItem (before insert, before update) {   

//if(checkRecursiveBI.runOnceBI()||checkRecursiveBU.runOnceBU())
//{
    Set<ID> setOliIds = new Set<ID>();
        for(OpportunityLineItem oli:Trigger.new){
            setOliIds.add(oli.Id);
        }
        Map<ID, OpportunityLineItem> mapOli = new Map<ID, OpportunityLineItem>([SELECT Id, Opportunity.Max_Deliv_Hx__c, Max_Deliv__c
                                                                                FROM OpportunityLineItem
                                                                                WHERE Id in:setOliIds]);
        if(mapOli.size()>0){

/*        List<OpportunityLineItem> oli1 = [SELECT Id, Max_Deliv__c
                                         FROM OpportunityLineItem
                                         WHERE Id IN: Trigger.newMap.keySet()]; 
                                     
            for (OpportunityLineItem oli :oli1){*/
            for(OpportunityLineItem oli1:Trigger.New){
                IF(mapOli.containsKey(oli1.Id) && (oli1.Max_Deliv__c == 0 || oli1.Max_Deliv__c == null)){
                    oli1.Max_Deliv__c = mapOli.get(oli1.Id).Opportunity.Max_Deliv_Hx__c + 1;
                }
            }
        }
//}

}

Test Class (TestOppUpdates)
// This class tests the trigger named OppUpdates.

@isTest(seeAllData=true)
public class TestOppUpdates {

    public static testMethod void TestOppUpdates() {       
                    
//Data Prep - Create Account, Opportunity, Product, etc.

        Account acct = TestCreateRecords.createAcct(0);
        insert acct;
        
    //Create Opportunity on Account
        Opportunity Opp = TestCreateRecords.createOpp(acct.Id);
       insert Opp;         
                       
    // Create Deliverables 

    List<product2> Insertprodlist= new list<product2>();

        //High-Risk Coaching
        Product2 deliv1 = new Product2 (name='Coaching-HR');
        deliv1.ProductCode = 'COACH_HR';
        deliv1.Product_Group__c = 'Coaching';
        Insertprodlist.add(deliv1);

        //Moderate-Risk Coaching
        Product2 deliv2 = new Product2 (name='Coaching-MR');
        deliv2.productcode = 'COACH_MR';
        deliv2.Product_Group__c = 'Coaching';
        Insertprodlist.add(deliv2);

        //Low-Risk Coaching
        Product2 deliv3 = new Product2 (name='Coaching-LR');
        deliv3.productcode = 'COACH_LR';
        deliv3.Product_Group__c = 'Coaching';
        Insertprodlist.add(deliv3);

        //Other Coaching
        Product2 deliv4 = new Product2 (name='Coaching-OTHER');
        deliv4.productcode = 'COACH_SELFREF';
        deliv4.Product_Group__c = 'Coaching';
        Insertprodlist.add(deliv4);

        //Weight Management
        Product2 deliv5 = new Product2 (name='Weight Management');
        deliv5.productcode = 'WEIGHTMGMTNODEVICE';
        deliv5.Product_Group__c = 'Weight Management';
        Insertprodlist.add(deliv5);

        //Tobacco Cessation
        Product2 deliv6 = new Product2 (name='Tobacco');
        deliv6.productcode = 'TOB_COACH';
        deliv6.Product_Group__c = 'Tobacco Cessation';
        Insertprodlist.add(deliv6);

        //Condition Management - Diabetes
        Product2 deliv7 = new Product2 (name='CM-Diabetes');
        deliv7.productcode = 'DIAB_COACH';
        deliv7.Product_Group__c = 'Condition Management';
        Insertprodlist.add(deliv7);

        //Condition Management - CHF
        Product2 deliv8 = new Product2 (name='CM-CHF');
        deliv8.productcode = 'HF_COACH';
        deliv8.Product_Group__c = 'Condition Management';
        Insertprodlist.add(deliv8);

        //Condition Management - CAD
        Product2 deliv9 = new Product2 (name='CM-CAD');
        deliv9.productcode = 'CAD_COACH';
        deliv9.Product_Group__c = 'Condition Management';
        Insertprodlist.add(deliv9);

        //Condition Management - COPD
        Product2 deliv10 = new Product2 (name='CM-COPD');
        deliv10.productcode = 'COPD_COACH';
        deliv10.Product_Group__c = 'Condition Management';
        Insertprodlist.add(deliv10);

        //Condition Management - Asthma
        Product2 deliv11 = new Product2 (name='CM-Asthma');
        deliv11.productcode = 'ASTH_COND_COACH';
        deliv11.Product_Group__c = 'Condition Management';
        Insertprodlist.add(deliv11);

        //Condition Management - Telephonic Bundle
        Product2 deliv12 = new Product2 (name='CM-Tel Bundle');
        deliv12.productcode = 'CMBUNDLE';
        deliv12.Product_Group__c = 'Condition Management';
        Insertprodlist.add(deliv12);

        //Health Concierge
        Product2 deliv13 = new Product2 (name='Health Concierge');
        deliv13.productcode = 'HCPLC_CGS';
        deliv13.Product_Group__c = 'Health Concierge';
        Insertprodlist.add(deliv13);
        
        //OWC
        Product2 deliv14 = new Product2 (name='Onsite Wellness Coordinators');
        deliv14.productcode = 'WELL_COORD';
        deliv14.Product_Group__c = 'Onsite Wellness Coordinators';
        Insertprodlist.add(deliv14);
        
        //Platform
        Product2 deliv15 = new Product2 (name='Core Package');
        deliv15.productcode = 'CORE_PKG';
        deliv15.Product_Group__c = 'Platform';
        Insertprodlist.add(deliv15);
        
        //Biometrics
        Product2 deliv16 = new Product2 (name='Biometrics');
        deliv16.productcode = 'BIOMETRIC_ONSITE';
        deliv16.Product_Group__c = 'Biometrics';
        Insertprodlist.add(deliv16);
        
        //Diabetes
        Product2 deliv17 = new Product2 (name='Diabetes');
        deliv17.productcode = 'DIAB_COACH';
        deliv17.Product_Group__c = 'Diabetes';
        Insertprodlist.add(deliv17);
        
        //Wellness Challenges
        Product2 deliv18 = new Product2 (name='Wellness Challenges');
        deliv18.productcode = 'WELLNESS';
        deliv18.Product_Group__c = 'Wellness Challenge';
        Insertprodlist.add(deliv18);
        
        //International - Platform
/*        Product2 deliv19 = new Product2 (name='International-Platform');
        deliv19.productcode = 'INT_PLAT';
        deliv19.Product_Group__c = 'International - Platform';
        Insertprodlist.add(deliv19);
        
        //International - Coaching
        Product2 deliv20 = new Product2 (name='International-Coaching');
        deliv20.productcode = 'INT_COACH';
        deliv20.Product_Group__c = 'International - Coaching';
        Insertprodlist.add(deliv20);*/
        
        insert Insertprodlist;
        
    // Get Pricebook
         Pricebook2 testpb = [select id from Pricebook2 where IsStandard = true];   
         
         List<PricebookEntry> InsertPricebookList= new List<PricebookEntry>();

// Add to pricebook
         PricebookEntry testdeliv1 = new PricebookEntry ();
         testdeliv1.pricebook2id = testpb.id;
         testdeliv1.product2id = deliv1.id;
         testdeliv1.IsActive = True;
         testdeliv1.UnitPrice = 10000;
         testdeliv1.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv1);
         
         PricebookEntry testdeliv2 = new PricebookEntry ();
         testdeliv2.pricebook2id = testpb.id;
         testdeliv2.product2id = deliv2.id;
         testdeliv2.IsActive = True;
         testdeliv2.UnitPrice = 10000;
         testdeliv2.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv2);
         
         PricebookEntry testdeliv3 = new PricebookEntry ();
         testdeliv3.pricebook2id = testpb.id;
         testdeliv3.product2id = deliv3.id;
         testdeliv3.IsActive = True;
         testdeliv3.UnitPrice = 10000;
         testdeliv3.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv3);
         
         PricebookEntry testdeliv4 = new PricebookEntry ();
         testdeliv4.pricebook2id = testpb.id;
         testdeliv4.product2id = deliv4.id;
         testdeliv4.IsActive = True;
         testdeliv4.UnitPrice = 10000;
         testdeliv4.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv4);
       
         PricebookEntry testdeliv5 = new PricebookEntry ();
         testdeliv5.pricebook2id = testpb.id;
         testdeliv5.product2id = deliv5.id;
         testdeliv5.IsActive = True;
         testdeliv5.UnitPrice = 10000;
         testdeliv5.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv5);
         
         PricebookEntry testdeliv6 = new PricebookEntry ();
         testdeliv6.pricebook2id = testpb.id;
         testdeliv6.product2id = deliv6.id;
         testdeliv6.IsActive = True;
         testdeliv6.UnitPrice = 10000;
         testdeliv6.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv6);
         
         PricebookEntry testdeliv7 = new PricebookEntry ();
         testdeliv7.pricebook2id = testpb.id;
         testdeliv7.product2id = deliv7.id;
         testdeliv7.IsActive = True;
         testdeliv7.UnitPrice = 10000;
         testdeliv7.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv7);
         
         PricebookEntry testdeliv8 = new PricebookEntry ();
         testdeliv8.pricebook2id = testpb.id;
         testdeliv8.product2id = deliv8.id;
         testdeliv8.IsActive = True;
         testdeliv8.UnitPrice = 10000;
         testdeliv8.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv8);
         
         PricebookEntry testdeliv9 = new PricebookEntry ();
         testdeliv9.pricebook2id = testpb.id;
         testdeliv9.product2id = deliv9.id;
         testdeliv9.IsActive = True;
         testdeliv9.UnitPrice = 10000;
         testdeliv9.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv9);
         
         PricebookEntry testdeliv10 = new PricebookEntry ();
         testdeliv10.pricebook2id = testpb.id;
         testdeliv10.product2id = deliv10.id;
         testdeliv10.IsActive = True;
         testdeliv10.UnitPrice = 10000;
         testdeliv10.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv10);
         
         PricebookEntry testdeliv11 = new PricebookEntry ();
         testdeliv11.pricebook2id = testpb.id;
         testdeliv11.product2id = deliv11.id;
         testdeliv11.IsActive = True;
         testdeliv11.UnitPrice = 10000;
         testdeliv11.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv11);
         
         PricebookEntry testdeliv12 = new PricebookEntry ();
         testdeliv12.pricebook2id = testpb.id;
         testdeliv12.product2id = deliv12.id;
         testdeliv12.IsActive = True;
         testdeliv12.UnitPrice = 10000;
         testdeliv12.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv12);
         
         PricebookEntry testdeliv13 = new PricebookEntry ();
         testdeliv13.pricebook2id = testpb.id;
         testdeliv13.product2id = deliv13.id;
         testdeliv13.IsActive = True;
         testdeliv13.UnitPrice = 10000;
         testdeliv13.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv13);
         
         PricebookEntry testdeliv14 = new PricebookEntry ();
         testdeliv14.pricebook2id = testpb.id;
         testdeliv14.product2id = deliv14.id;
         testdeliv14.IsActive = True;
         testdeliv14.UnitPrice = 10000;
         testdeliv14.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv14);
         
         PricebookEntry testdeliv15 = new PricebookEntry ();
         testdeliv15.pricebook2id = testpb.id;
         testdeliv15.product2id = deliv15.id;
         testdeliv15.IsActive = True;
         testdeliv15.UnitPrice = 10000;
         testdeliv15.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv15);
         
         PricebookEntry testdeliv16 = new PricebookEntry ();
         testdeliv16.pricebook2id = testpb.id;
         testdeliv16.product2id = deliv16.id;
         testdeliv16.IsActive = True;
         testdeliv16.UnitPrice = 10000;
         testdeliv16.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv16);
         
         PricebookEntry testdeliv17 = new PricebookEntry ();
         testdeliv17.pricebook2id = testpb.id;
         testdeliv17.product2id = deliv17.id;
         testdeliv17.IsActive = True;
         testdeliv17.UnitPrice = 10000;
         testdeliv17.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv17);
         
         PricebookEntry testdeliv18 = new PricebookEntry ();
         testdeliv18.pricebook2id = testpb.id;
         testdeliv18.product2id = deliv18.id;
         testdeliv18.IsActive = True;
         testdeliv18.UnitPrice = 10000;
         testdeliv18.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv18);
         
/*         PricebookEntry testdeliv19 = new PricebookEntry ();
         testdeliv19.pricebook2id = testpb.id;
         testdeliv19.product2id = deliv19.id;
         testdeliv19.IsActive = True;
         testdeliv19.UnitPrice = 10000;
         testdeliv19.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv19);
         
         PricebookEntry testdeliv20 = new PricebookEntry ();
         testdeliv20.pricebook2id = testpb.id;
         testdeliv20.product2id = deliv20.id;
         testdeliv20.IsActive = True;
         testdeliv20.UnitPrice = 10000;
         testdeliv20.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv20);*/

         Insert InsertPricebookList;
         

test.starttest();

        List<OpportunityLineItem> oli1 = new List<OpportunityLineItem>();
            integer todo = 20;
            for(integer bi=0; bi<todo; bi++) {
        
            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv1.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv2.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv3.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv4.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv5.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv6.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv7.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv8.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv9.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv10.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv11.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv12.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv13.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv14.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv15.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv16.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv17.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv18.id, OpportunityId = Opp.id) );

/*            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv19.id, OpportunityId = Opp.id, Prod_Grp__c = 'International - Platform') );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv20.id, OpportunityId = Opp.id, Prod_Grp__c = 'International - Coaching') );*/
         }
    
        insert oli1;
        
        delete oli1;

test.stoptest();
    }
}




  • July 25, 2014
  • Like
  • 0
Hello,

I have a trigger (see below) that works in my Sandbox and is covered by my test in my sandbox.  When I try to deploy to production, I get the error:

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, UniqueDelivID: execution of BeforeUpdate caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.UniqueDelivID: line 15, column 1: []

Can anyone help as to why I am getting this error?

Trigger:
//Assigns a unique ID to each deliverable in every Opportunity so DyNad can track.
trigger UniqueDelivID on OpportunityLineItem (before insert, before update) {   

    Set<ID> setOliIds = new Set<ID>();
        for(OpportunityLineItem oli:Trigger.new){
            setOliIds.add(oli.Id);
        }
        Map<ID, OpportunityLineItem> mapOli = new Map<ID, OpportunityLineItem>([SELECT Id, Opportunity.Max_Deliv_Hx__c, Max_Deliv__c
                                                                                FROM OpportunityLineItem
                                                                                WHERE Id in:setOliIds]);
        if(mapOli.size()>0){

            for(OpportunityLineItem oli1:Trigger.New){
                IF(mapOli.containsKey(oli1.Id) && oli1.Max_Deliv__c == null){
                    oli1.Max_Deliv__c = mapOli.get(oli1.Id).Opportunity.Max_Deliv_Hx__c + 1;
                }
            }
        }

}


  • July 23, 2014
  • Like
  • 0
Hello,

I have a trigger on a custom object (Client_Revenue__c).  When a record is created, edited, or deleted for this object, the trigger links the record of the current year (based on a field called Revenue_Year__c in the custom object) to a custom lookup field on the Account.  The test I created is only covering 25% of the trigger.  Lines 12 - 25 and 32-42 are not being covered.  Does anyone know why this would be happening?  Thanks,

Trigger:
trigger Contract2Account on Contract_Summary__c (after insert, after update, after delete) 
{          
    Try
    {
     Map<Id,Account> oppMap = new Map<Id,Account>();
     Set<id> Ids = new Set<id>();

if(trigger.isInsert || trigger.isUpdate)
{
    if(checkRecursiveAI.runOnceAI() || checkRecursiveAU.runOnceAU())
    {
        for (Contract_Summary__c prgm : Trigger.new){
            if(prgm.Type_of_Contract__c == 'Renewal' || prgm.Type_of_Contract__c == 'Initial MSA')
            Ids.add(prgm.Account_Name__c);
        }
     
        Map<id,Account> acctMap2 = new Map<id,Account>([Select Id,Name,Contract_Summary__c, Contract_Summary__r.Current_Effective_Date__c from Account Where Id in :Ids]);  
        for (Contract_Summary__c  prgm2 : Trigger.new){
            if(acctMap2.containsKey(prgm2.Account_Name__c) && (acctMap2.get(prgm2.Account_Name__c).Contract_summary__r.Current_Effective_Date__c < prgm2.Current_Effective_Date__c || acctMap2.get(prgm2.Account_Name__c).Contract_summary__r.Current_Effective_Date__c == null)) {
                Account a = acctMap2.get(prgm2.Account_Name__c);
                a.Contract_Summary__c = prgm2.Id;
                oppMap.put(a.id,a);
            }
        }
        update oppMap.values();
    }
}
     
if(trigger.isDelete)
{
    if(checkRecursiveAD.runOnceAD()){
        for (Contract_Summary__c prgm : Trigger.old){
            if(prgm.Type_of_Contract__c == 'Renewal' || prgm.Type_of_Contract__c == 'Initial MSA')
            Ids.add(prgm.Account_Name__c);
        }
        Map<id,Account> acctMap2 = new Map<id,Account>([Select Id,Name,Contract_Summary__c from Account Where Id in :Ids]);  
        for (Contract_Summary__c  prgm2 : Trigger.old){
                Account a = acctMap2.get(prgm2.Account_Name__c);
                a.Contract_Summary__c = null;
                oppMap.put(a.id,a);
        }
        update oppMap.values();
    }
}
    }
    catch(Exception e)
    {}
}

Test Class:

@isTest(SeeallData=true)
private class ContractSummary_Tests2 {

    private static testmethod void testSummary1() {

    Account a1 = new Account();
        a1.name = 'test';
        a1.Type = 'Employer';
    insert a1;
   
    Opportunity opp1 = new Opportunity();
            opp1.Name = 'Test Opportunity';
            opp1.StageName = 'Stage 6 - Live';
            opp1.CloseDate = date.newinstance(2020,1,31);
            opp1.Type = 'New Business';
            opp1.accountId=a1.Id;
        insert opp1;

    Opportunity opp2 = new Opportunity();
            opp2.Name = 'Test Opportunity';
            opp2.StageName = 'Stage 6 - Live';
            opp2.CloseDate = date.newinstance(2022,1,31);
            opp2.Type = 'Renewal';
            opp2.accountId=a1.Id;
        insert opp2;

    Contract_Summary__c testContSumm1 = new Contract_Summary__c ();
        testContSumm1.Related_Opportunity__c = opp1.Id;
        testContSumm1.Account_Name__c = opp1.Account.id;
        testContSumm1.Current_Effective_Date__c = date.newinstance(2020,1,31);
        testContSumm1.Current_Expiration_Date__c = date.newinstance(2022,1,31);
        testContSumm1.Type_of_Contract__c = 'Initial MSA';
        testContSumm1.Client_Signature_Date__c = date.newinstance(2020,1,31);
    insert testContSumm1;

    Contract_Summary__c testContSumm2= new Contract_Summary__c ();
        testContSumm2.Related_Opportunity__c = opp2.Id;
        testContSumm2.Account_Name__c = opp2.Account.id;
        testContSumm2.Current_Effective_Date__c = date.newinstance(2022,1,31);
        testContSumm2.Current_Expiration_Date__c = date.newinstance(2024,1,31);
        testContSumm2.Type_of_Contract__c = 'Renewal';
        testContSumm2.Client_Signature_Date__c = date.newinstance(2022,1,31);
    insert testContSumm2;

        
    Test.startTest();
    update opp1;
    update opp2;
    update testContSumm1;
    update testContSumm2;
    delete testContSumm2;
    Test.stopTest();

    }
}

Class to prevent infinite loops:
public Class checkRecursiveAI{
    private static boolean run = true;
    public static boolean runOnceAI(){
    if(run){
     run=false;
     return true;
    }
    else{
        return run;
    }
    }
}



  • July 21, 2014
  • Like
  • 0
Hello,

I have a custom object (Contract_Summary__c) that has a Master-Detail with Opportunity.  I have created a test class to test a trigger and I'm trying to populate the Account Name field on my Contract_Summary__c from the Opportunity field.  Can anyone give me the syntax to do this?  My code from the test class is below and Line 4 is where I'm having trouble:

public static Contract_Summary__c createContSumm(Id oppId){ 
        Contract_Summary__c ContSumm = new Contract_Summary__c();
            ContSumm.Related_Opportunity__c = oppId;
            ContSumm.Account_Name__c = oppId.AcctId.id;
            ContSumm.Current_Effective_Date__c = date.newinstance(2025,1,31);
            ContSumm.Current_Expiration_Date__c = date.newinstance(2027,1,31);
            ContSumm.Type_of_Contract__c = 'Initial MSA';
            ContSumm.Client_Signature_Date__c = date.newinstance(2025,1,31);
        return ContSumm;


  • July 21, 2014
  • Like
  • 0
Hello,

I have a custom object called Contract_Summary__c.  I have a trigger (below) which fires when a contract summary record is created, edited or delete, and updates a number of fields on the associated Opportunity based on the values in the custom object.  The trigger works as expected, but the test class I created (see below) only covers the Insert and Update functions of the trigger and not the Delete.  Lines 49-78 are not being covered.  Does anyone know why this happens or how to fix the test class to cover those lines?

Trigger:

trigger ContractUpdates on Contract_Summary__c (after insert, after update, after delete)
{

if(checkRecursiveBI.runOnceBI() || checkRecursiveBU.runOnceBU() || checkRecursiveBD.runOnceBD())
{
   
//Update Opportunity fields from values in Contract Summary object

    Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>();    
    set<Id> Ids = new Set <Id>(); 

    if(trigger.isInsert || trigger.isUpdate)
        {
    FOR(Contract_Summary__c con :trigger.new) {
        Ids.add(con.Related_Opportunity__c); 
    }
    system.debug('@@@@@Ids: '+Ids);
    Map<id,Opportunity> oppMap2 = new Map<id,Opportunity>([Select Id,Start_Date__c, End_Date__c from Opportunity Where Id in :Ids]); 
    system.debug('@@@@@oppMap2: '+oppMap2);
    system.debug('@@@@@Trigger.newMap.keySet(): '+Trigger.new);
    List<Contract_Summary__c> cs1 = [SELECT Id, Related_Opportunity__c,Current_Effective_Date__c, Current_Expiration_Date__c, Current_Term_Months__c, Auto_Renew_Notice_Days__c, Auto_Renew_Provision__c, Term_for_Convenience__c, Portal_SLAs__c, Coaching_Performance_Guarantees__c, Off_Shore_Resource_Restiction__c, Delegated_Entity_Agreement__c, Special_Terms__c
                                     FROM Contract_Summary__c
                                     WHERE Id IN: Trigger.new]; 
        
        
        for(Contract_Summary__c con :cs1) 
        {
            Opportunity o = oppMap2.get(con.Related_Opportunity__c);

            o.Start_Date__c = con.Current_Effective_Date__c;
            o.End_Date__c = con.Current_Expiration_Date__c;
            o.Current_Term_Months__c = con.Current_Term_Months__c;
            o.Auto_Renew__c = con.Auto_Renew_Provision__c;
            o.Auto_Renew_Notice_Days__c = con.Auto_Renew_Notice_Days__c;
            o.Term_for_Convenience__c = con.Term_for_Convenience__c;
            o.Portal_SLAs__c = con.Portal_SLAs__c;
            o.Coaching_Performance_Guarantees__c = con.Coaching_Performance_Guarantees__c;
            o.Off_Shore_Resource_Restiction__c = con.Off_Shore_Resource_Restiction__c;
            o.Delegated_Entity_Agreement__c = con.Delegated_Entity_Agreement__c;
            o.Special_Terms__c = con.Special_Terms__c;

            oppMap.put(o.id,o);
        }
            update oppMap.values();
        }

    IF(trigger.isDelete)
        {
    FOR(Contract_Summary__c con :trigger.old) {
        Ids.add(con.Related_Opportunity__c); 
    }
    
    Map<id,Opportunity> oppMap2 = new Map<id,Opportunity>([Select Id,Start_Date__c, End_Date__c from Opportunity Where Id in :Ids]); 

    List<Contract_Summary__c> cs2 = [SELECT Id,Related_Opportunity__c
                                     FROM Contract_Summary__c
                                     WHERE Id IN: Trigger.oldMap.keySet()]; 
        
        
        for(Contract_Summary__c con :cs2) 
        {
            Opportunity o = oppMap2.get(con.Related_Opportunity__c);

            o.Start_Date__c = null;
            o.End_Date__c = null;
            o.Current_Term_Months__c = null;
            o.Auto_Renew__c = FALSE;
            o.Auto_Renew_Notice_Days__c = null;
            o.Term_for_Convenience__c = FALSE;
            o.Portal_SLAs__c = FALSE;
            o.Coaching_Performance_Guarantees__c = FALSE;
            o.Off_Shore_Resource_Restiction__c = FALSE;
            o.Delegated_Entity_Agreement__c = FALSE;
            o.Special_Terms__c = FALSE;

            oppMap.put(o.id,o);
        }
            update oppMap.values();
        }
}

}

Test Class:

@isTest(SeeallData=true)
private class ContractSummary_Tests {

    private static testmethod void testSummary1() {

    Account a = [Select id, name, Type, Consultant_Partner_Primary__c FROM Account WHERE Type='Consultant/Broker' limit 1];
    Account a1 = new Account();
    a1.name ='test';
    a1.Consultant_Partner_Primary__c =a.id;
    insert a1;
   
    Opportunity opp = new Opportunity();
            opp.Name = 'Test Opportunity';
            opp.StageName = 'Stage 1 - Learn';
            opp.CloseDate = date.newinstance(2013,1,31);
            opp.Type = 'Renewal';
            opp.accountId=a1.id;
            opp.Consultant_Type__c = 'Primary Consultant';
            
        insert opp;
 a1.Consultant_Partner_Primary__c=a.Consultant_Partner_Primary__c;
 update a1;

        Contract_Summary__c testContSumm = TestContractCreate.createContSumm(opp.id);
        system.debug('@@@@testContSumm : '+testContSumm);
        insert testContSumm;

        Contract_Summary__c testContSumm2 = [SELECT id,Amendment_Number__c
                                             FROM Contract_Summary__c
                                             WHERE id =: testContSumm.Id];
        testContSumm2.Amendment_Number__c = 'Amendment #2';

        Contract_Summary__c testContSumm3 = TestContractCreate.createContSumm2(opp.id);
        system.debug('@@@@testContSumm3 : '+testContSumm3);
        insert testContSumm3;
        
    Test.startTest();
    update opp;
    update testContSumm2;
    delete testContSumm3;
    Test.stopTest();

    }
}



  • July 17, 2014
  • Like
  • 0
Hello,

I have a trigger that fires when a campaign is created and changes the default Member Status of Responded on the campaign to Registered, and also adds another status of Attended.  The trigger works well, but my test class is not covering line 19-26.  Does anyone know how I can get the test to cover these lines?

Trigger:
trigger CampaignMemberStatus on Campaign (after insert) {

if(checkRecursiveAI.runOnceAI())
{
   
    List<Campaign> newCamps = [select Id from Campaign where Id IN :trigger.new AND ParentID = Null];
    List<CampaignMemberStatus> cms = new List<CampaignMemberStatus>();
    Set<Id> camps = new Set<Id>();
    List<CampaignMemberStatus> cms2Delete = new List<CampaignMemberStatus>();
    List<CampaignMemberStatus> cms2Insert = new List<CampaignMemberStatus>();
   
    for(Campaign camp : newCamps){
      
            camps.add(camp.Id);
    }  
   
   
   for (CampaignMemberStatus cm: [Select Id, Label, CampaignID  FROM CampaignMemberStatus WHERE CampaignID IN :camps]){
      if(cm.Label == 'Responded' ){
            CampaignMemberStatus cms1 = new CampaignMemberStatus(CampaignId=cm.CampaignID, Label='Registered', HasResponded=false, IsDefault = False, SortOrder=4);          
            System.debug(cms1);
            cms2Delete.add(cm);
            cms2Insert.add(cms1);
           
            CampaignMemberStatus cms3 = new CampaignMemberStatus(CampaignId = cm.CampaignId, HasResponded=true, Label = 'Attended', SortOrder = 5);
            cms2Insert.add(cms3);

      }

    }
    //perform insert before delete because system requires at least one CMS for a Campaign
    insert cms2Insert;
    delete cms2Delete;

}

}

Test Class:

@isTest private class CampaignMembStatus{

    @isTest private static void test_Memb_Status() {
    
        Campaign camp=new Campaign(Name='Test Campaign',IsActive=True);
        insert camp;

    Test.StartTest();
    Test.StopTest();
        
    }
}


  • July 16, 2014
  • Like
  • 0
Hello,

I have a trigger the queries the OpportunityLineItem records on an Opportunity, looks for certain product families, and then updates the Opportunity record with the roll-up amount from each family and checks a box if that family is represented in the OpportunityLineItems.  The trigger works fine.  The test below covers 54% of the trigger, but what it is not covering is everything in the trigger after the line "IF(trigger.isdelete){".  I didn't post the trigger because it is very large.  Does anyone know why the "delete oli1;" line (line 94) in the test class below would not cover the delete portion of the trigger and how to fix it?  Thanks!

// This class tests the trigger named OppUpdates.

@isTest(seeAllData=true)
private class TestOppUpdates {

    static testMethod void TestOppUpdates() {       
                    
//Data Prep - Create Account, Opportunity, Product, etc.

        Account acct = new Account(name='Test Account', Type = 'Employer');
        insert acct;
        
    //Create Opportunity on Account
        Opportunity Opp = new Opportunity(Name='Test Account - New Opp1');
        Opp.StageName = 'Stage 1 - Learn';
        Opp.CloseDate = Date.today();
        Opp.AccountId = acct.id;
        insert Opp;         
                       
    // Create Deliverables 

    List<product2> Insertprodlist= new list<product2>();

        //High-Risk Coaching
        Product2 deliv1 = new Product2 (name='Coaching-HR');
        deliv1.ProductCode = 'COACH_HR';
        deliv1.Product_Group__c = 'Coaching';
        Insertprodlist.add(deliv1);

        //Moderate-Risk Coaching
        Product2 deliv2 = new Product2 (name='Coaching-MR');
        deliv2.productcode = 'COACH_MR';
        deliv2.Product_Group__c = 'Coaching';
        Insertprodlist.add(deliv2);

        //Low-Risk Coaching
        Product2 deliv3 = new Product2 (name='Coaching-LR');
        deliv3.productcode = 'COACH_LR';
        deliv3.Product_Group__c = 'Coaching';
        Insertprodlist.add(deliv3);

        
        insert Insertprodlist;
        
    // Get Pricebook
         Pricebook2 testpb = [select id from Pricebook2 where IsStandard = true];   
         
         List<PricebookEntry> InsertPricebookList= new List<PricebookEntry>();

// Add to pricebook
         PricebookEntry testdeliv1 = new PricebookEntry ();
         testdeliv1.pricebook2id = testpb.id;
         testdeliv1.product2id = deliv1.id;
         testdeliv1.IsActive = True;
         testdeliv1.UnitPrice = 10000;
         testdeliv1.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv1);
         
         PricebookEntry testdeliv2 = new PricebookEntry ();
         testdeliv2.pricebook2id = testpb.id;
         testdeliv2.product2id = deliv2.id;
         testdeliv2.IsActive = True;
         testdeliv2.UnitPrice = 10000;
         testdeliv2.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv2);
         
         PricebookEntry testdeliv3 = new PricebookEntry ();
         testdeliv3.pricebook2id = testpb.id;
         testdeliv3.product2id = deliv3.id;
         testdeliv3.IsActive = True;
         testdeliv3.UnitPrice = 10000;
         testdeliv3.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv3);

         Insert InsertPricebookList;
         

test.starttest();
        List<OpportunityLineItem> oli1 = new List<OpportunityLineItem>();
            integer todo = 20;
            for(integer bi=0; bi<todo; bi++) {
        
            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv1.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv2.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv3.id, OpportunityId = Opp.id) );
         }
        insert oli1;
        
        delete oli1;
        
test.stoptest();
    }
}


  • July 16, 2014
  • Like
  • 0
Hello,

I have a trigger that queries LineItems on an Opportunity and updates the Opportunity with counts.  The test class below returns coverage of 54% and is not covering deletion of line items.  I have a delete statement on line 78 that I thought would work, but is there something else I need to do?

Test Class:
// This class tests the trigger named OppUpdates.

@isTest(seeAllData=true)
private class TestOppUpdates {

    static testMethod void TestOppUpdates() {       
                    
//Data Prep - Create Account, Opportunity, Product, etc.

        Account acct = new Account(name='Test Account', Type = 'Employer');
        insert acct;
        
    //Create Opportunity on Account
        Opportunity Opp = new Opportunity(Name='Test Account - New Opp1');
        Opp.StageName = 'Stage 1 - Learn';
        Opp.CloseDate = Date.today();
        Opp.AccountId = acct.id;
        insert Opp;         
                       
    // Create Deliverables 

    List<product2> Insertprodlist= new list<product2>();

        //High-Risk
        Product2 deliv1 = new Product2 (name='HR');
        deliv1.ProductCode = 'COACH_HR';
        deliv1.Product_Group__c = 'HR';
        Insertprodlist.add(deliv1);

        //Moderate-Risk
        Product2 deliv2 = new Product2 (name='MR');
        deliv2.productcode = 'COACH_MR';
        deliv2.Product_Group__c = 'MR';
        Insertprodlist.add(deliv2);

        
        insert Insertprodlist;
        
    // Get Pricebook
         Pricebook2 testpb = [select id from Pricebook2 where IsStandard = true];   
         
         List<PricebookEntry> InsertPricebookList= new List<PricebookEntry>();

// Add to pricebook
         PricebookEntry testdeliv1 = new PricebookEntry ();
         testdeliv1.pricebook2id = testpb.id;
         testdeliv1.product2id = deliv1.id;
         testdeliv1.IsActive = True;
         testdeliv1.UnitPrice = 10000;
         testdeliv1.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv1);
         
         PricebookEntry testdeliv2 = new PricebookEntry ();
         testdeliv2.pricebook2id = testpb.id;
         testdeliv2.product2id = deliv2.id;
         testdeliv2.IsActive = True;
         testdeliv2.UnitPrice = 10000;
         testdeliv2.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv2);
         
         Insert InsertPricebookList;
         

test.starttest();
        List<OpportunityLineItem> oli1 = new List<OpportunityLineItem>();
       // integer todo = 300;
       integer todo = 20;
        for(integer bi=0; bi<todo; bi++) {
            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv1.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv2.id, OpportunityId = Opp.id) );
         }
    
      insert oli1;  
   
      delete oli1; 
        
        test.stoptest();

    }
}


  • July 11, 2014
  • Like
  • 0
Hello,

I have a trigger on my campaign object that updates member statuses.  The trigger works fine, but my test class is only generating 64% coverage.  The test class is not covering lines 19-26 .  Does anyone know how I can increase coverage in my test class to at least get above the 75% threshold?  Thanks.

Trigger:
trigger CampaignMemberStatus on Campaign (after insert) {

if(checkRecursiveAI.runOnceAI())
{
   
    List<Campaign> newCamps = [select Id from Campaign where Id IN :trigger.new AND ParentID = Null];
    List<CampaignMemberStatus> cms = new List<CampaignMemberStatus>();
    Set<Id> camps = new Set<Id>();
    List<CampaignMemberStatus> cms2Delete = new List<CampaignMemberStatus>();
    List<CampaignMemberStatus> cms2Insert = new List<CampaignMemberStatus>();
   
    for(Campaign camp : newCamps){
      
            camps.add(camp.Id);
    }  
    
   for (CampaignMemberStatus cm: [Select Id, Label, CampaignID  FROM CampaignMemberStatus WHERE CampaignID IN :camps]){
      if(cm.Label == 'Responded' ){
            CampaignMemberStatus cms1 = new CampaignMemberStatus(CampaignId=cm.CampaignID, Label='Registered', HasResponded=false, IsDefault = False, SortOrder=4);          
            System.debug(cms1);
            cms2Delete.add(cm);
            cms2Insert.add(cms1);
           
            CampaignMemberStatus cms3 = new CampaignMemberStatus(CampaignId = cm.CampaignId, HasResponded=true, Label = 'Attended', SortOrder = 5);
            cms2Insert.add(cms3);

      }
   }
    //perform insert before delete because system requires at least one CMS for a Campaign
    insert cms2Insert;
    delete cms2Delete;

}
}

Test Class:
@isTest private class CampaignMembStatus{

    @isTest private static void test_Memb_Status() {
    
        Campaign camp=new Campaign(Name='Test Campaign',IsActive=True);
        Insert camp;

        Account acct = new Account(name='Test Account', Type = 'Employer');
        insert acct;

        Contact cont = new Contact(FirstName='Test',LastName='Contact',AccountId=acct.Id);
        insert cont;
 
        CampaignMember cMemb = new CampaignMember(CampaignId=camp.Id, ContactId=cont.Id,Status='Responded');
        Insert cMemb ; 

        CampaignMemberStatus cMembStat = new CampaignMemberStatus(CampaignId=camp.Id, Label='Responded',HasResponded=false,IsDefault=False,SortOrder=4);
        Insert cMembStat ; 

        Test.StartTest();
        update cMembStat;
        Test.StopTest();
        
    }
}



  • July 11, 2014
  • Like
  • 0
Hello,

I have a trigger and test class below.  I am only getting 7% coverage on my trigger and I don't understand why.  Can anyone help?

Trigger:
trigger UpdateConsultOpp on Opportunity (before insert, before update) {   

if(checkRecursiveBI.runOnceBI()||checkRecursiveBU.runOnceBU())
{
   
    Set<ID> setOppIds = new Set<ID>();
/*    List<Opportunity> opp1 = [SELECT Id
                             FROM Opportunity
                             WHERE Id IN: Trigger.newMap.keySet()]; 
                                     
    for (Opportunity opp :opp1){*/
    for(Opportunity opp:Trigger.new){
        setOppIds.add(opp.Id);
    }
    Map<ID, Opportunity> mapAcc = new Map<ID, Opportunity>([Select Id, Account.Consultant_Partner_Primary__c, Account.Consultant_Partner_Secondary__c, Consultant_Type__c
                                                            FROM Opportunity
                                                            WHERE Id in:setOppIds]);
    if(mapAcc.size()>0){
    List<Opportunity> opp2 = [SELECT Id,Consultant_Type__c,Consultant_Partner__c
                             FROM Opportunity
                             WHERE Id IN: Trigger.new]; 
                                     
        for (Opportunity opp :opp2){
//        for(Opportunity opp:Trigger.New){
            IF(mapAcc.containsKey(opp.Id) && opp.Consultant_Type__c == 'Primary Consultant'){
                opp.Consultant_Partner__c = mapAcc.get(opp.Id).Account.Consultant_Partner_Primary__c;
            }
            ELSE IF(mapAcc.containsKey(opp.Id) && opp.Consultant_Type__c == 'Secondary Consultant'){
                opp.Consultant_Partner__c = mapAcc.get(opp.Id).Account.Consultant_Partner_Secondary__c;
            }
        }
    }
}

}

Test Class:
@isTest private class TestOppConsultants {

    @isTest private static void testOppConsults() {
       
    Account acct1 = TestAcctTeamCreate.createAcct(0);
    insert acct1;
        
    Account acct2 = TestConsultAcctCreate.createConsult1(0);
    insert acct2;
  
    Account acct3 = TestConsultAcctCreate.createConsult2(0);
    insert acct3;
  
    Opportunity opp1 = TestOppCreate3.createOpp(acct1.Id);
    insert opp1;

        Account acctPrim = [SELECT Id, Consultant_Partner_Primary__c
                            FROM Account
                            WHERE Id =: acct1.Id];
            acctPrim.Consultant_Partner_Primary__c = acct2.Id;
        update acctPrim;

        
        Opportunity oppPrim = [SELECT Id, Consultant_Type__c
                                FROM Opportunity
                                WHERE Id =: opp1.Id];
            oppPrim.Consultant_Type__c = 'Primary Consultant';
        update oppPrim;
            

        Account acctPrim1 = [SELECT Id, Consultant_Partner_Primary__c
                            FROM Account
                            WHERE Id =: acct1.Id];
            acctPrim1.Consultant_Partner_Primary__c = acct3.Id;
        update acctPrim1;


        Account acctSec = [SELECT Id, Consultant_Partner_Secondary__c
                           FROM Account
                           WHERE Id =: acct1.Id];
            acctSec.Consultant_Partner_Secondary__c = acct3.Id;
        update acctSec;

        
        Opportunity oppSec = [SELECT Id, Consultant_Type__c
                                FROM Opportunity
                                WHERE Id =: opp1.Id];
            oppSec.Consultant_Type__c = 'Secondary Consultant';
        update oppSec;


        Account acctSec1 = [SELECT Id, Consultant_Partner_Secondary__c
                           FROM Account
                           WHERE Id =: acct1.Id];
            acctSec1.Consultant_Partner_Secondary__c = acct2.Id;
        update acctSec1;

        
    Test.startTest();
        update acct1;
        update acct2;
        update acct3;
        update opp1;
        update acctPrim;
        update oppPrim;
        update acctPrim1;
        update acctSec;    
        update oppSec;    
        update acctSec1;    
    Test.stopTest();
    }
}



  • July 02, 2014
  • Like
  • 0
Hello,

I am running into the error above when trying to run a test class.  The stack trace lists one of my triggers, but when I comment out the DML statements in that trigger (posted below), it comes up with a different trigger in the stack trace.  I am not a seasoned programmer, so I really don't know how to trace back where this problem is coming from.  Can anyone help or give me some guidance?  Thanks.

Trigger in Stack Trace:

trigger AccountTeamChanges on Account(after insert, after update) 
{
   //list to hold new account team members
     List<AccountTeamMember> acctMembers = new List<AccountTeamMember>();
     
     //list to hold new account sharing rules
     List<AccountShare> acctSharingRules = new List<AccountShare>();
     
     //misc
     Set<String> rmMemberAccts = new Set<String>();
     Map<ID, List<ID>> AccountTeamMap = new Map<ID, List<ID>>(); 
    
    List<Account> acc = new list<Account>();
    
     for(Account a : Trigger.new)
     {

        if(Trigger.isInsert)
        {
            //new Account - Client Advisor
            if(a.Client_Advisor__c != null){
            
            AccountTeamMember ca = new AccountTeamMember();
            ca.AccountId = a.Id;
            ca.TeamMemberRole = 'Client Advisor';
            ca.UserId = a.Client_Advisor__c;
            acctMembers.add(ca);
            
            AccountShare caSharingRule = new AccountShare();
            caSharingRule.AccountId = a.Id;
            acctSharingRules.add(caSharingRule);
            }

            //new Account - Market Director
            if(a.Market_Director__c != null){
            
            AccountTeamMember md = new AccountTeamMember();
            md.AccountId = a.Id;
            md.TeamMemberRole = 'Market Director';
            md.UserId = a.Market_Director__c;
            acctMembers.add(md);
            
            AccountShare mdSharingRule = new AccountShare();
            mdSharingRule.AccountId = a.Id;
            acctSharingRules.add(mdSharingRule);
            }

            //new Account - Industry Manager
            if(a.Industry_Manager__c != null){
            
            AccountTeamMember im = new AccountTeamMember();
            im.AccountId = a.Id;
            im.TeamMemberRole = 'Industry Manager';
            im.UserId = a.Industry_Manager__c;
            acctMembers.add(im);
            
            AccountShare imSharingRule = new AccountShare();
            imSharingRule.AccountId = a.Id;
            acctSharingRules.add(imSharingRule);
            }
            system.debug('@@@@@@@@@ ACCTMEMBERS TRIGGER.INSERT: ' + acctMembers);
        }

        //updated Account
        else if(Trigger.isUpdate)
        {
            
            //old Account record
            Account oldAcct = Trigger.oldMap.get(a.Id);
            
            //check to see if the team values have changed and verifies the
            //new values are not null

            system.debug('client advisor '+ a.Client_Advisor__c +'old value '+ oldAcct.Client_Advisor__c);

            if(oldAcct.Client_Advisor__c != a.Client_Advisor__c && a.Client_Advisor__c != null)
            {
                list<AccountTeamMember> oldadvisor = [SELECT Id, UserId, AccountId, TeamMemberRole
                                            FROM AccountTeamMember
                                            WHERE (TeamMemberRole='Client Advisor') AND AccountId =:a.id];
            if (oldadvisor .size() > 0){
            delete oldadvisor ;
			}
            
            //add old Client Advisor to remove list if one exists
                rmMemberAccts.add(oldAcct.Id);
                    if(AccountTeamMap.get(oldAcct.Id) == null){
                        AccountTeamMap.put(oldAcct.Id, new List<ID>{oldAcct.Client_Advisor__c});
                        }
                    else{
                        AccountTeamMap.get(oldAcct.Id).add(oldAcct.Client_Advisor__c);
                        }
                system.debug('Account teammap 1 : '+ AccountTeamMap);
                

                
                //add new processor to account team and update sharing rules
                AccountTeamMember ca = new AccountTeamMember();
                ca.AccountId = a.Id;
                ca.TeamMemberRole = 'Client Advisor';
                ca.UserId = a.Client_Advisor__c;
                acctMembers.add(ca);
                
                AccountShare caSharingRule = new AccountShare();
                caSharingRule.AccountId = a.Id;
                acctSharingRules.add(caSharingRule);
            }
            else if(oldAcct.Client_Advisor__c != a.Client_Advisor__c && a.Client_Advisor__c == null)
            {
                rmMemberAccts.add(a.Id);
                    if(AccountTeamMap.get(oldAcct.Id) == null){
                        AccountTeamMap.put(oldAcct.Id, new List<ID>{oldAcct.Client_Advisor__c});}
                    else{
                AccountTeamMap.get(oldAcct.Id).add(oldAcct.Client_Advisor__c);}

            }

            
            //check to see if the team values have changed and verifies the
            //new values are not null
            if(oldAcct.Market_Director__c != a.Market_Director__c && a.Market_Director__c != null)
            {
                list<AccountTeamMember> oldMD = [SELECT Id, UserId, AccountId, TeamMemberRole
                                            FROM AccountTeamMember
                                            WHERE (TeamMemberRole='Market Director') AND AccountId =:a.id];
            if (oldMD .size() > 0){
            delete oldMD;
			}

            //add old Market Director to remove list if one exists

                rmMemberAccts.add(oldAcct.Id);
                    if(AccountTeamMap.get(oldAcct.Id) == null){
                        AccountTeamMap.put(oldAcct.Id, new List<ID>{oldAcct.Market_Director__c});}
                    else{
                        AccountTeamMap.get(oldAcct.Id).add(oldAcct.Market_Director__c);}
                system.debug('Account teammap 2 : '+ AccountTeamMap);

                
                //add new processor to account team and update sharing rules
                AccountTeamMember md = new AccountTeamMember();
                md.AccountId = a.Id;
                md.TeamMemberRole = 'Market Director';
                md.UserId = a.Market_Director__c;
                acctMembers.add(md);
                
                AccountShare mdSharingRule = new AccountShare();
                mdSharingRule.AccountId = a.Id;
                acctSharingRules.add(mdSharingRule);
            }
            else if(oldAcct.Market_Director__c != a.Market_Director__c && a.Market_Director__c == null)
            {

                rmMemberAccts.add(a.Id);
                    if(AccountTeamMap.get(oldAcct.Id) == null){
                        AccountTeamMap.put(oldAcct.Id, new List<ID>{oldAcct.Market_Director__c});}
                    else{
                AccountTeamMap.get(oldAcct.Id).add(oldAcct.Client_Advisor__c);}

            }

            
            //check to see if the team values have changed and verifies the
            //new values are not null
            if(oldAcct.Industry_Manager__c != a.Industry_Manager__c && a.Industry_Manager__c != null)
            {
                list<AccountTeamMember> oldIM = [SELECT Id, UserId, AccountId, TeamMemberRole
                                            FROM AccountTeamMember
                                            WHERE (TeamMemberRole='Industry Manager') AND AccountId =:a.id];
            if (oldIM .size() > 0){
            delete oldIM;
			}

                //add old Industry Manager to remove list if one exists
                if(oldAcct.Industry_Manager__c != null)

                rmMemberAccts.add(oldAcct.Id);
                    if(AccountTeamMap.get(oldAcct.Id) == null){
                        AccountTeamMap.put(oldAcct.Id, new List<ID>{oldAcct.Industry_Manager__c});}
                    else{
                        AccountTeamMap.get(oldAcct.Id).add(oldAcct.Industry_Manager__c);}
                system.debug('Account teammap 2 : '+ AccountTeamMap);

                
                //add new processor to account team and update sharing rules
                AccountTeamMember im = new AccountTeamMember();
                im.AccountId = a.Id;
                im.TeamMemberRole = 'Industry Manager';
                im.UserId = a.Industry_Manager__c;
                acctMembers.add(im);
                
                AccountShare imSharingRule = new AccountShare();
                imSharingRule.AccountId = a.Id;
                acctSharingRules.add(imSharingRule);
            }
            else if(oldAcct.Industry_Manager__c != a.Industry_Manager__c && a.Industry_Manager__c == null)
            {

                rmMemberAccts.add(a.Id);
                    if(AccountTeamMap.get(oldAcct.Id) == null){
                        AccountTeamMap.put(oldAcct.Id, new List<ID>{oldAcct.Market_Director__c});}
                    else{
                AccountTeamMap.get(oldAcct.Id).add(oldAcct.Client_Advisor__c);}


            }
            system.debug('@@@@@@@@@ ACCTMEMBERS TRIGGER.UPDATE: ' + acctMembers);
        }
        
        //DML OPERATIONS
        //remove team members from account team if any exist
        
        acc.add(a);

    }

        system.debug('-->ACCOUNT MEMBERS: ' + acctMembers);
        //insert the new account team members if any exist
        if(acctMembers.size() > 0)
            upsert acctMembers;
        
        //insert account sharing rules if any exist
        if(acctSharingRules.size() > 0)
            upsert acctSharingRules;
            
        if (acc[0].Client_Advisor__c == null )
        {
            list<AccountTeamMember> atm1 = [SELECT Id, UserId, AccountId, TeamMemberRole
                                            FROM AccountTeamMember
                                            WHERE (TeamMemberRole='Client Advisor') AND AccountId =:acc[0].id];
            if (atm1.size() > 0){
            delete atm1;
			}
        }
        if (acc[0].Industry_Manager__c == null )
        {
            list<AccountTeamMember> atm1 = [SELECT Id, UserId, AccountId, TeamMemberRole
                                            FROM AccountTeamMember
                                            WHERE (TeamMemberRole='Industry Manager') AND AccountId =:acc[0].id];
            if (atm1.size() > 0){
            delete atm1;
			}
        }
        if (acc[0].Market_Director__c == null )
        {
            list<AccountTeamMember> atm1 = [SELECT Id, UserId, AccountId, TeamMemberRole
                                            FROM AccountTeamMember
                                            WHERE (TeamMemberRole='Market Director') AND AccountId =:acc[0].id];
            if (atm1.size() > 0){
            delete atm1;
			}
        }    
}

Test Class:


  • June 23, 2014
  • Like
  • 0
Hello,

I have a test class that currently covers multiple triggers.  How can I get this calss to cover only 1 trigger?  It's causing an issue because some of the triggers are Before Insert triggers and others are After Insert so I am getting Null Pointer Exception errors because of it.  Thanks,
  • June 13, 2014
  • Like
  • 0
Hello,

I have created a test class and trigger (see below).  The trigger works as expected but when I run the test I get the error:

System.LimitException: Too many SOQL queries: 101
Trigger.UpdateConsultantAcct: line 8, column 1


Does anyone know why I would be getting this error and how to resolve it?  Thanks in advance for any help!


Test Class:

@Istest(SeeAllData=true)
public class TestAccountPlan {

public static testMethod void testMyController1() {    
       
  Account acct1 = TestGeneralAcctCreate.createAcct(0);
    insert acct1;

    Account acct2 = TestStatusAcctCreate.createAcct(0);
  
    insert acct2;

        Profile ProDir2 = [SELECT Id
                          FROM Profile
                          WHERE Name='Client Delivery (Director)'];
               
            User Dir2 = new User(Alias = 'Dir2User',Country='United States',Email='Dir2User@testing.com',EmailEncodingKey='UTF-8', LastName='Testing1a', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = ProDir2.Id,TimeZoneSidKey='America/New_York', UserName='Dir2User@testing.com');
        insert Dir2;

        Profile ProTeamMgr2 = [SELECT Id
                              FROM Profile
                              WHERE Name='Client Delivery Team Manager'];
               
            User TM2 = new User(Alias = 'TM2User',Country='United States',Email='TM2User@testing.com',EmailEncodingKey='UTF-8', LastName='Testing2a', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = ProTeamMgr2.Id,TimeZoneSidKey='America/New_York', UserName='TM2User@testing.com');
        insert TM2;

        Profile ProCSM2 = [SELECT Id
                          FROM Profile
                          WHERE Name='Client Success Manager'];
               
            User CSM2 = new User(Alias = 'CSM2User',Country='United States',Email='CSM2User@testing.com',EmailEncodingKey='UTF-8', LastName='Testing3a', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = ProCSM2.Id,TimeZoneSidKey='America/New_York', UserName='CSM2User@testing.com');
        insert CSM2;

        Account acct2a = [SELECT id,Market_Director__c,Industry_Manager__c,Client_Advisor__c
                          FROM Account
                          WHERE id =: acct2.Id];
               acct2a.Market_Director__c = Dir2.Id;
               acct2a.Industry_Manager__c = TM2.Id;
               acct2a.Client_Advisor__c = CSM2.Id;
        
    Account acct3 = TestGeneralAcctCreate.createAcct(0);
    insert acct3;

    Account acct4 = TestGeneralAcctCreate.createAcct(0);
    insert acct4;

    Account acct5 = TestGeneralAcctCreate.createAcct(0);
    insert acct5;

    Opportunity opp1 = TestOppCreate3.createOpp(acct1.Id);
    insert opp1;

    Contract_Summary__c contsumm1 = TestContractCreate.createContSumm(opp1.Id);
    insert contsumm1;
  
        Contract_Summary__c contSumm2 = [SELECT id
                                         FROM Contract_Summary__c
                                         WHERE id =: contSumm1.id];
  
    Client_Status_Scorecard__c cssc1 = TestStatusSCCreate.createCSSC1(acct1.Id);
    insert cssc1;
    
        Client_Status_Scorecard__c cssc1a = [SELECT id
                                           FROM Client_Status_Scorecard__c
                                           WHERE id =: cssc1.id];
    
    Client_Status_Scorecard__c cssc2 = TestStatusSCCreate.createCSSC2(acct2.Id);
    insert cssc2;
    
    Client_Status_Scorecard__c cssc3 = TestStatusSCCreate.createCSSC3(acct3.Id);
    insert cssc3;
    
    Client_Status_Scorecard__c cssc4 = TestStatusSCCreate.createCSSC4(acct4.Id);
    insert cssc4;
    
    Client_Status_Scorecard__c cssc5 = TestStatusSCCreate.createCSSC5(acct5.Id);
    insert cssc5;
    
    Account_Plan__c plan1 = TestAcctPlanCreate.createAP1(acct1.Id);

    ApexPages.StandardController AcctPlan = new ApexPages.standardController(acct1);
    AcctPlanController APControl1 = new AcctPlanController(AcctPlan);
    APControl1.ap2 = plan1;
    APControl1.testsf();
    APControl1.save();
    
    Test.startTest();
    update acct1;
    update acct2;
    update acct2a;
    update acct3;
    update acct4;
    update acct5;
    update opp1;
    update contsumm1;
    delete contsumm2;
    update cssc1;
    update cssc3;
    update cssc4;
    update cssc5;
    delete cssc1a;
    Test.stopTest();
  
}

}

Trigger:
trigger UpdateConsultantAcct on Account (after update){
        
    List<Account> acct = new List<Account>();

    Opportunity[] oppsToUpdate = new List<Opportunity>();   

    // Query Opportunity records realted to Account that is being created/edited
    List<Opportunity> opps = [SELECT AccountId, IsWon, IsClosed, Consultant_Partner__c, Consultant_Type__c
                              FROM Opportunity
                              WHERE AccountId IN: Trigger.newMap.keySet()];
        
    FOR(Account a : acct){
//    FOR(Account a : Trigger.new){

        // Iterating through all the Opportunity records and updating them as per the conditions
        for(Opportunity opps2 :opps){

            // Update Consultant Partner field on Opportunity if Opp is Open and Consultant field changes at Account level
            IF(opps2.IsWon == FALSE && opps2.IsClosed == FALSE && opps2.Consultant_Type__c == 'Primary Consultant' && trigger.NewMap.get(opps2.AccountId).Consultant_Partner_Primary__c != trigger.OldMap.get(opps2.AccountId).Consultant_Partner_Primary__c){
                opps2.Consultant_Partner__c = a.Consultant_Partner_Primary__c;
                oppsToUpdate.add(opps2); 
            }
            
            ELSE IF(opps2.IsWon == FALSE && opps2.IsClosed == FALSE && opps2.Consultant_Type__c == 'Secondary Consultant' && trigger.NewMap.get(opps2.AccountId).Consultant_Partner_Secondary__c != trigger.OldMap.get(opps2.AccountId).Consultant_Partner_Secondary__c){
                opps2.Consultant_Partner__c = a.Consultant_Partner_Secondary__c;
                oppsToUpdate.add(opps2); 
            }
        }
        
    }
    update oppsToUpdate; 
}



  • June 13, 2014
  • Like
  • 0
Hello,

I am getting the above error when I run the test below and it seems to be related to the trigger below.  Can anyone help?

Rest of error message:  Trigger.AccountTeamChanges: line 268, column 1

Test Class:
@Istest(SeeAllData=true)
public class TestAccountPlan {

public static testMethod void testMyController1() {    
       
  Account acct1 = TestGeneralAcctCreate.createAcct(0);
    insert acct1;

    Account acct2 = TestStatusAcctCreate.createAcct(0);
  
    insert acct2;

        Profile ProDir2 = [SELECT Id
                          FROM Profile
                          WHERE Name='Client Delivery (Director)'];
               
            User Dir2 = new User(Alias = 'Dir2User',Country='United States',Email='Dir2User@testing.com',EmailEncodingKey='UTF-8', LastName='Testing1a', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = ProDir2.Id,TimeZoneSidKey='America/New_York', UserName='Dir2User@testing.com');
        insert Dir2;

        Profile ProTeamMgr2 = [SELECT Id
                              FROM Profile
                              WHERE Name='Client Delivery Team Manager'];
               
            User TM2 = new User(Alias = 'TM2User',Country='United States',Email='TM2User@testing.com',EmailEncodingKey='UTF-8', LastName='Testing2a', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = ProTeamMgr2.Id,TimeZoneSidKey='America/New_York', UserName='TM2User@testing.com');
        insert TM2;

        Profile ProCSM2 = [SELECT Id
                          FROM Profile
                          WHERE Name='Client Success Manager'];
               
            User CSM2 = new User(Alias = 'CSM2User',Country='United States',Email='CSM2User@testing.com',EmailEncodingKey='UTF-8', LastName='Testing3a', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = ProCSM2.Id,TimeZoneSidKey='America/New_York', UserName='CSM2User@testing.com');
        insert CSM2;

        Account acct2a = [SELECT id,Market_Director__c,Industry_Manager__c,Client_Advisor__c
                          FROM Account
                          WHERE id =: acct2.Id];
               acct2a.Market_Director__c = Dir2.Id;
               acct2a.Industry_Manager__c = TM2.Id;
               acct2a.Client_Advisor__c = CSM2.Id;
        
    Account acct3 = TestGeneralAcctCreate.createAcct(0);
    insert acct3;

    Account acct4 = TestGeneralAcctCreate.createAcct(0);
    insert acct4;

    Account acct5 = TestGeneralAcctCreate.createAcct(0);
    insert acct5;

//    Account acct6 = TestStatusAcctCreate.createAcct(0);
//    insert acct6;

    Opportunity opp1 = TestOppCreate3.createOpp(acct1.Id);
    insert opp1;

    Contract_Summary__c contsumm1 = TestContractCreate.createContSumm(opp1.Id);
    insert contsumm1;
  
        Contract_Summary__c contSumm2 = [SELECT id
                                         FROM Contract_Summary__c
                                         WHERE id =: contSumm1.id];
  
    Client_Status_Scorecard__c cssc1 = TestStatusSCCreate.createCSSC1(acct1.Id);
    insert cssc1;
    
        Client_Status_Scorecard__c cssc1a = [SELECT id
                                           FROM Client_Status_Scorecard__c
                                           WHERE id =: cssc1.id];
    
    Client_Status_Scorecard__c cssc2 = TestStatusSCCreate.createCSSC2(acct2.Id);
    insert cssc2;
    
    Client_Status_Scorecard__c cssc3 = TestStatusSCCreate.createCSSC3(acct3.Id);
    insert cssc3;
    
    Client_Status_Scorecard__c cssc4 = TestStatusSCCreate.createCSSC4(acct4.Id);
    insert cssc4;
    
    Client_Status_Scorecard__c cssc5 = TestStatusSCCreate.createCSSC5(acct5.Id);
    insert cssc5;
    
//    Client_Status_Scorecard__c cssc6 = TestStatusSCCreate.createCSSC6(acct6.Id);
//    insert cssc6;
    
    Account_Plan__c plan1 = TestAcctPlanCreate.createAP1(acct1.Id);

    ApexPages.StandardController AcctPlan = new ApexPages.standardController(acct1);
    AcctPlanController APControl1 = new AcctPlanController(AcctPlan);
  //  APControl1.ap.add(plan1);
    APControl1.ap2 = plan1;
    APControl1.testsf();
    APControl1.save();
    
    Test.startTest();
    update acct1;
    update acct2;
    update acct2a;
    update acct3;
    update acct4;
    update acct5;
//    update acct6;
    update opp1;
    update contsumm1;
    delete contsumm2;
    update cssc1;
//    update cssc2;
    update cssc3;
    update cssc4;
    update cssc5;
//    update cssc6;
    delete cssc1a;
    Test.stopTest();
  
}

}


Trigger in error:
trigger AccountTeamChanges on Account(after insert, after update) 
{
   //list to hold new account team members
     List<AccountTeamMember> acctMembers = new List<AccountTeamMember>();
     
     //list to hold new account sharing rules
     List<AccountShare> acctSharingRules = new List<AccountShare>();
     
     //misc
     Set<String> rmMemberAccts = new Set<String>();
     Map<ID, List<ID>> AccountTeamMap = new Map<ID, List<ID>>(); 
    
    List<Account> acc = new list<Account>();
    
     //iterate through records to find update processor values
     for(Account a : Trigger.new)
     {
        
        if(Trigger.isInsert)
        {
            //new Account - Client Advisor
            if(a.Client_Advisor__c != null){
            
            AccountTeamMember ca = new AccountTeamMember();
            ca.AccountId = a.Id;
            ca.TeamMemberRole = 'Client Advisor';
            ca.UserId = a.Client_Advisor__c;
            acctMembers.add(ca);
            
            AccountShare caSharingRule = new AccountShare();
            caSharingRule.AccountId = a.Id;
            caSharingRule.OpportunityAccessLevel = 'Read';
            caSharingRule.CaseAccessLevel = 'Read';
            caSharingRule.AccountAccessLevel = 'Edit';
            caSharingRule.UserOrGroupId = a.Client_Advisor__c;
            acctSharingRules.add(caSharingRule);
            }

            //new Account - Market Director
            if(a.Market_Director__c != null){
            
            AccountTeamMember md = new AccountTeamMember();
            md.AccountId = a.Id;
            md.TeamMemberRole = 'Market Director';
            md.UserId = a.Market_Director__c;
            acctMembers.add(md);
            
            AccountShare mdSharingRule = new AccountShare();
            mdSharingRule.AccountId = a.Id;
            mdSharingRule.OpportunityAccessLevel = 'Read';
            mdSharingRule.CaseAccessLevel = 'Read';
            mdSharingRule.AccountAccessLevel = 'Edit';
            mdSharingRule.UserOrGroupId = a.Market_Director__c;
            acctSharingRules.add(mdSharingRule);
            }

            //new Account - Industry Manager
            if(a.Industry_Manager__c != null){
            
            AccountTeamMember im = new AccountTeamMember();
            im.AccountId = a.Id;
            im.TeamMemberRole = 'Industry Manager';
            im.UserId = a.Industry_Manager__c;
            acctMembers.add(im);
            
            AccountShare imSharingRule = new AccountShare();
            imSharingRule.AccountId = a.Id;
            imSharingRule.OpportunityAccessLevel = 'Read';
            imSharingRule.CaseAccessLevel = 'Read';
            imSharingRule.AccountAccessLevel = 'Edit';
            imSharingRule.UserOrGroupId = a.Industry_Manager__c;
            acctSharingRules.add(imSharingRule);
            }
            system.debug('@@@@@@@@@ ACCTMEMBERS TRIGGER.INSERT: ' + acctMembers);
        }

        //updated Account
        else if(Trigger.isUpdate)
        {
            
            //old Account record
            Account oldAcct = Trigger.oldMap.get(a.Id);
            
            //check to see if the team values have changed and verifies the
            //new values are not null

            system.debug('client advisor '+ a.Client_Advisor__c +'old value '+ oldAcct.Client_Advisor__c);

            if(oldAcct.Client_Advisor__c != a.Client_Advisor__c && a.Client_Advisor__c != null)
            {
                //Sample code added by SFDC support
                list<AccountTeamMember> oldadvisor = [SELECT Id, UserId, AccountId, TeamMemberRole
                                            FROM AccountTeamMember
                                            WHERE (TeamMemberRole='Client Advisor') AND AccountId =:a.id];
            if (oldadvisor .size() > 0)
            {delete oldadvisor ;}
            //add old Client Advisor to remove list if one exists
                rmMemberAccts.add(oldAcct.Id);
                    if(AccountTeamMap.get(oldAcct.Id) == null){
                        AccountTeamMap.put(oldAcct.Id, new List<ID>{oldAcct.Client_Advisor__c});
                        }
                    else{
                        AccountTeamMap.get(oldAcct.Id).add(oldAcct.Client_Advisor__c);
                        }
                system.debug('Account teammap 1 : '+ AccountTeamMap);
                

                
                //add new processor to account team and update sharing rules
                AccountTeamMember ca = new AccountTeamMember();
                ca.AccountId = a.Id;
                ca.TeamMemberRole = 'Client Advisor';
                ca.UserId = a.Client_Advisor__c;
                acctMembers.add(ca);
                
                AccountShare caSharingRule = new AccountShare();
                caSharingRule.AccountId = a.Id;
                caSharingRule.OpportunityAccessLevel = 'Read';
                caSharingRule.CaseAccessLevel = 'Read';
                caSharingRule.AccountAccessLevel = 'Edit';
                caSharingRule.UserOrGroupId = a.Client_Advisor__c;
                acctSharingRules.add(caSharingRule);
            }
            else if(oldAcct.Client_Advisor__c != a.Client_Advisor__c && a.Client_Advisor__c == null)
            {
                rmMemberAccts.add(a.Id);
                    if(AccountTeamMap.get(oldAcct.Id) == null){
                        AccountTeamMap.put(oldAcct.Id, new List<ID>{oldAcct.Client_Advisor__c});}
                    else{
                AccountTeamMap.get(oldAcct.Id).add(oldAcct.Client_Advisor__c);}

            }

            
            //check to see if the team values have changed and verifies the
            //new values are not null
            if(oldAcct.Market_Director__c != a.Market_Director__c && a.Market_Director__c != null)
            {
                //Sample code added by SFDC support
                list<AccountTeamMember> oldMD = [SELECT Id, UserId, AccountId, TeamMemberRole
                                            FROM AccountTeamMember
                                            WHERE (TeamMemberRole='Market Director') AND AccountId =:a.id];
            if (oldMD .size() > 0)
            {delete oldMD ;}

            //add old Market Director to remove list if one exists

                rmMemberAccts.add(oldAcct.Id);
                    if(AccountTeamMap.get(oldAcct.Id) == null){
                        AccountTeamMap.put(oldAcct.Id, new List<ID>{oldAcct.Market_Director__c});}
                    else{
                        AccountTeamMap.get(oldAcct.Id).add(oldAcct.Market_Director__c);}
                system.debug('Account teammap 2 : '+ AccountTeamMap);

                
                //add new processor to account team and update sharing rules
                AccountTeamMember md = new AccountTeamMember();
                md.AccountId = a.Id;
                md.TeamMemberRole = 'Market Director';
                md.UserId = a.Market_Director__c;
                acctMembers.add(md);
                
                AccountShare mdSharingRule = new AccountShare();
                mdSharingRule.AccountId = a.Id;
                mdSharingRule.OpportunityAccessLevel = 'Read';
                mdSharingRule.CaseAccessLevel = 'Read';
                mdSharingRule.AccountAccessLevel = 'Edit';
                mdSharingRule.UserOrGroupId = a.Market_Director__c;
                acctSharingRules.add(mdSharingRule);
            }
            else if(oldAcct.Market_Director__c != a.Market_Director__c && a.Market_Director__c == null)
            {

                rmMemberAccts.add(a.Id);
                    if(AccountTeamMap.get(oldAcct.Id) == null){
                        AccountTeamMap.put(oldAcct.Id, new List<ID>{oldAcct.Market_Director__c});}
                    else{
                AccountTeamMap.get(oldAcct.Id).add(oldAcct.Client_Advisor__c);}

            }

            
            //check to see if the team values have changed and verifies the
            //new values are not null
            if(oldAcct.Industry_Manager__c != a.Industry_Manager__c && a.Industry_Manager__c != null)
            {
                //Sample code added by SFDC support
                list<AccountTeamMember> oldIM = [SELECT Id, UserId, AccountId, TeamMemberRole
                                            FROM AccountTeamMember
                                            WHERE (TeamMemberRole='Industry Manager') AND AccountId =:a.id];
            if (oldIM .size() > 0)
            {delete oldIM ;}

                //add old Industry Manager to remove list if one exists
                if(oldAcct.Industry_Manager__c != null)

                rmMemberAccts.add(oldAcct.Id);
                    if(AccountTeamMap.get(oldAcct.Id) == null){
                        AccountTeamMap.put(oldAcct.Id, new List<ID>{oldAcct.Industry_Manager__c});}
                    else{
                        AccountTeamMap.get(oldAcct.Id).add(oldAcct.Industry_Manager__c);}
                system.debug('Account teammap 2 : '+ AccountTeamMap);

                
                //add new processor to account team and update sharing rules
                AccountTeamMember im = new AccountTeamMember();
                im.AccountId = a.Id;
                im.TeamMemberRole = 'Industry Manager';
                im.UserId = a.Industry_Manager__c;
                acctMembers.add(im);
                
                AccountShare imSharingRule = new AccountShare();
                imSharingRule.AccountId = a.Id;
                imSharingRule.OpportunityAccessLevel = 'Read';
                imSharingRule.CaseAccessLevel = 'Read';
                imSharingRule.AccountAccessLevel = 'Edit';
                imSharingRule.UserOrGroupId = a.Industry_Manager__c;
                acctSharingRules.add(imSharingRule);
            }
            else if(oldAcct.Industry_Manager__c != a.Industry_Manager__c && a.Industry_Manager__c == null)
            {

                rmMemberAccts.add(a.Id);
                    if(AccountTeamMap.get(oldAcct.Id) == null){
                        AccountTeamMap.put(oldAcct.Id, new List<ID>{oldAcct.Market_Director__c});}
                    else{
                AccountTeamMap.get(oldAcct.Id).add(oldAcct.Client_Advisor__c);}


            }
            system.debug('@@@@@@@@@ ACCTMEMBERS TRIGGER.UPDATE: ' + acctMembers);
        }
        
        //DML OPERATIONS
        //remove team members from account team if any exist
        
        acc.add(a);

    }

        system.debug('-->ACCOUNT MEMBERS: ' + acctMembers);
        //insert the new account team members if any exist
        if(acctMembers.size() > 0)
            upsert acctMembers; //LINE 100
        
        //insert account sharing rules if any exist
        if(acctSharingRules.size() > 0)
            upsert acctSharingRules;
            
        if (acc[0].Client_Advisor__c == null )
        {
            list<AccountTeamMember> atm1 = [SELECT Id, UserId, AccountId, TeamMemberRole
                                            FROM AccountTeamMember
                                            WHERE (TeamMemberRole='Client Advisor') AND AccountId =:acc[0].id];
            if (atm1.size() > 0)
            {delete atm1;}
        }
        if (acc[0].Industry_Manager__c == null )
        {
            list<AccountTeamMember> atm1 = [SELECT Id, UserId, AccountId, TeamMemberRole
                                            FROM AccountTeamMember
                                            WHERE (TeamMemberRole='Industry Manager') AND AccountId =:acc[0].id];
            if (atm1.size() > 0)
            {delete atm1;}
        }
        if (acc[0].Market_Director__c == null )
        {
            list<AccountTeamMember> atm1 = [SELECT Id, UserId, AccountId, TeamMemberRole
                                            FROM AccountTeamMember
                                            WHERE (TeamMemberRole='Market Director') AND AccountId =:acc[0].id];
            if (atm1.size() > 0)
            {delete atm1;}
        }    
}


  • June 11, 2014
  • Like
  • 0
Hello,

I created 2 Classes (below) for testing purposes.  The first class creates an Account record, with 3 dummy user records that get populated into 3 custom user lookup fields on the Account.  The second class is a test class that is meant to cover a trigger that fires when the values for the users are changed on the Account.  Everything saves OK, but when I run the test, I get an error stating:

System.QueryException: List has no rows for assignment to SObject
Class.TestStatusAcctCreate.createAcct: line 6, column 1
Class.TestAccountPlan.testMyController1: line 9, column 1

Does anyone know why I would be getting this error?  Thanks.

public class TestStatusAcctCreate {

        // create and insert a new Accountrecord that has an arbitrary value for Type.
    public static Account createAcct(Integer i){ 

        Profile ProDir = [SELECT Id
                          FROM Profile
                          WHERE Name='Client Delivery (Director)'];
               
            User Dir1 = new User(Alias = 'DirUser',Country='United States',Email='DirUser@testing.com',EmailEncodingKey='UTF-8', LastName='Testing1', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = ProDir.Id,TimeZoneSidKey='America/New_York', UserName='DirUser@testing.com');
        insert Dir1;

        Profile ProTeamMgr = [SELECT Id
                              FROM Profile
                              WHERE Name='Client Delivery Team Manager'];
               
            User TM1 = new User(Alias = 'TMUser',Country='United States',Email='TMUser@testing.com',EmailEncodingKey='UTF-8', LastName='Testing2', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = ProTeamMgr.Id,TimeZoneSidKey='America/New_York', UserName='TMUser@testing.com');
        insert TM1;

        Profile ProCSM = [SELECT Id
                          FROM Profile
                          WHERE Name='Client Success Manager'];
               
            User CSM1 = new User(Alias = 'CSMUser',Country='United States',Email='CSMUser@testing.com',EmailEncodingKey='UTF-8', LastName='Testing3', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = ProCSM.Id,TimeZoneSidKey='America/New_York', UserName='CSMUser@testing.com');
        insert CSM1;


    Account acct = new Account();
            acct.Name = 'Test' + i;
            acct.Type= 'Employer';
            acct.Client_Advisor__c = CSM1.Id;
            acct.Industry_Manager__c = TM1.Id;
            acct.Market_Director__c = Dir1.Id;
            
        return acct;
        
    }
}




@Istest(SeeAllData=true)
public class TestAccountPlan {

public static testMethod void testMyController1() {    
       
    Account acct1 = TestGeneralAcctCreate.createAcct(0);
    insert acct1;

    Account acct2 = TestStatusAcctCreate.createAcct(0);
    insert acct2;

        Profile ProDir2 = [SELECT Id
                          FROM Profile
                          WHERE Name='Client Delivery (Director)'];
               
            User Dir2 = new User(Alias = 'Dir2User',Country='United States',Email='Dir2User@testing.com',EmailEncodingKey='UTF-8', LastName='Testing1a', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = ProDir2.Id,TimeZoneSidKey='America/New_York', UserName='Dir2User@testing.com');
        insert Dir2;

        Profile ProTeamMgr2 = [SELECT Id
                              FROM Profile
                              WHERE Name='Client Delivery Team Manager'];
               
            User TM2 = new User(Alias = 'TM2User',Country='United States',Email='TM2User@testing.com',EmailEncodingKey='UTF-8', LastName='Testing2a', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = ProTeamMgr2.Id,TimeZoneSidKey='America/New_York', UserName='TM2User@testing.com');
        insert TM2;

        Profile ProCSM2 = [SELECT Id
                          FROM Profile
                          WHERE Name='Client Success Manager'];
               
            User CSM2 = new User(Alias = 'CSM2User',Country='United States',Email='CSM2User@testing.com',EmailEncodingKey='UTF-8', LastName='Testing3a', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = ProCSM2.Id,TimeZoneSidKey='America/New_York', UserName='CSM2User@testing.com');
        insert CSM2;

        Account acct2a = [SELECT id,Market_Director__c,Industry_Manager__c,Client_Advisor__c
                          FROM Account
                          WHERE id =: acct2.Id];
               acct2a.Market_Director__c = Dir2.Id;
               acct2a.Industry_Manager__c = TM2.Id;
               acct2a.Client_Advisor__c = CSM2.Id;
        
    Account acct3 = TestGeneralAcctCreate.createAcct(0);
    insert acct3;

    Account acct4 = TestGeneralAcctCreate.createAcct(0);
    insert acct4;

    Account acct5 = TestGeneralAcctCreate.createAcct(0);
    insert acct5;

//    Account acct6 = TestStatusAcctCreate.createAcct(0);
//    insert acct6;

    Opportunity opp1 = TestOppCreate3.createOpp(acct1.Id);
    insert opp1;

    Contract_Summary__c contsumm1 = TestContractCreate.createContSumm(opp1.Id);
    insert contsumm1;
  
        Contract_Summary__c contSumm2 = [SELECT id
                                         FROM Contract_Summary__c
                                         WHERE id =: contSumm1.id];
  
    Client_Status_Scorecard__c cssc1 = TestStatusSCCreate.createCSSC1(acct1.Id);
    insert cssc1;
    
        Client_Status_Scorecard__c cssc1a = [SELECT id
                                           FROM Client_Status_Scorecard__c
                                           WHERE id =: cssc1.id];
    
    Client_Status_Scorecard__c cssc2 = TestStatusSCCreate.createCSSC2(acct2.Id);
    insert cssc2;
    
    Client_Status_Scorecard__c cssc3 = TestStatusSCCreate.createCSSC3(acct3.Id);
    insert cssc3;
    
    Client_Status_Scorecard__c cssc4 = TestStatusSCCreate.createCSSC4(acct4.Id);
    insert cssc4;
    
    Client_Status_Scorecard__c cssc5 = TestStatusSCCreate.createCSSC5(acct5.Id);
    insert cssc5;
    
//    Client_Status_Scorecard__c cssc6 = TestStatusSCCreate.createCSSC6(acct6.Id);
//    insert cssc6;
    
    Account_Plan__c plan1 = TestAcctPlanCreate.createAP1(acct1.Id);

    ApexPages.StandardController AcctPlan = new ApexPages.standardController(acct1);
    AcctPlanController APControl1 = new AcctPlanController(AcctPlan);
  //  APControl1.ap.add(plan1);
    APControl1.ap2 = plan1;
    APControl1.testsf();
    APControl1.save();
    
    Test.startTest();
    update acct1;
    update acct2;
    update acct2a;
    update acct3;
    update acct4;
    update acct5;
//    update acct6;
    update opp1;
    update contsumm1;
    delete contsumm2;
    update cssc1;
//    update cssc2;
    update cssc3;
    update cssc4;
    update cssc5;
//    update cssc6;
    delete cssc1a;
    Test.stopTest();
  
}

}



  • June 09, 2014
  • Like
  • 0
Hello,

I have a test class that creates and Account (below).  In this class, I have included actual User IDs, which is not ideal, especially when users are de-activated.  How do I create dummy User IDs with specific profiles that I can use in this Class rather than the actual IDs?


public class TestStatusAcctCreate {

        // create and insert a new Account record that has an arbitrary value for Type and users assigned to the 3 custom fields.
    public static Account createAcct(Integer i){ 
        Account acct = new Account();
            acct.Name = 'Test' + i;
            acct.Type= 'Employer';
            acct.Client_Advisor__c = '00570000001LlBD';
            acct.Industry_Manager__c = '00570000001JKVQ';
            acct.Market_Director__c = '00570000001r5xs';
            
        return acct;
        
    }
}


  • June 06, 2014
  • Like
  • 0
Hello,

I've created the trigger below on my OpportunityLineItem object.  There is a custom field on the Opportunity object called Max_Deliv_Hx__c which captures the highest number of Opportunity Products that have been included on an Opportunity.  I am trying to assign a value to each OpportunityLineItem from 1 to Max_Deliv_Hx__c, but only if that OpportunityLineItem does not already have a value.  When I run this trigger I get and error:

Error: Invalid Data.
Apex trigger UniqueDelivID caused an unexpected exception, contact your administrator: UniqueDelivID: execution of BeforeUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 00kn00000032bk8AAA; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = 00kn00000032bk8) is currently in trigger UniqueDelivID, therefore it cannot recursively update itself: []: Trigger.UniqueDelivID: line 18, column 1


Can anyone provide some help?  Thanks.


trigger UniqueDelivID on OpportunityLineItem (before insert, before update) {

    //get the Product Numbers and other fields from the OpportunityLineItem and build a list of OpportunityLineItems to update

    List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();

        for(OpportunityLineItem oli : [SELECT Id, Opportunity.Max_Deliv_Hx__c, Max_Deliv__c
                                       FROM OpportunityLineItem
                                       WHERE Id in : trigger.new]) {

        IF(oli.Max_Deliv__c = null){
            oli.Max_Deliv__c = oli.Opportunity.Max_Deliv_Hx__c + 1; //Update the OpportunityLineItem
        }
        oliList.add(oli);

    }

    update oliList; //Update the OpportunityLineItems with the Max_Deliv__c field

}
  • June 05, 2014
  • Like
  • 0
Hello,

Let me preface this by saying that while I am comfortable coding Apex for Triggers and test classes, I have never coded scheduled Apex and Apex callouts.  I have an external database that I want to bring into SFDC on a nightly basis.  I would like to set up a batch Apex trigger that fires early in the morning and updates either a standard or custom obect with data from the database.  Can anyone point me to resources where I can see sample code on how to accomplish this?  Thanks,
  • August 18, 2014
  • Like
  • 0
Hello,

I have the trigger below set to fire when OpportunityLineItem is updated or inserted.  It's meant to assign a unique number to a custom field called Max_Deliv__c on the OpportunityLineItem object.  The trigger works fine when I add single products, however, when I add multiple products at the same time it assigns the same number to each.  Does anyone know how I can change the trigger to assign a different sequential number to each product added?  Auto number fields will not work because I need the numbering sequence to start over on each new Opportunity.  Thanks,

//Assigns a unique ID to each deliverable in every Opportunity so DyNad can track.
trigger UniqueDelivID on OpportunityLineItem (before insert, before update) {   

if(checkRecursiveBI.runOnceBI()||checkRecursiveBU.runOnceBU())
{
    Set<ID> setOliIds = new Set<ID>();
        for(OpportunityLineItem oli:Trigger.new){
            setOliIds.add(oli.Id);
        }
        Map<ID, OpportunityLineItem> mapOli = new Map<ID, OpportunityLineItem>([SELECT Id, Opportunity.Max_Deliv_Hx__c, Max_Deliv__c
                                                                                FROM OpportunityLineItem
                                                                                WHERE Id in:setOliIds]);
        if(mapOli.size()>0){

/*        List<OpportunityLineItem> oli1 = [SELECT Id, Max_Deliv__c
                                         FROM OpportunityLineItem
                                         WHERE Id IN: Trigger.newMap.keySet()]; 
                                     
            for (OpportunityLineItem oli :oli1){*/
            for(OpportunityLineItem oli1:Trigger.New){
                IF(mapOli.containsKey(oli1.Id) && (oli1.Max_Deliv__c == 0 || oli1.Max_Deliv__c == null)){
                    oli1.Max_Deliv__c = mapOli.get(oli1.Id).Opportunity.Max_Deliv_Hx__c + 1;
                }
            }
        }
}

}


  • July 27, 2014
  • Like
  • 0
Hello,

I am trying to deploy a trigger (UniqueDelivID) from my sandbox to production.  The trigger works fine in my sandbox and is covered 100% by the test class.  Yet when I try to move to production, I get the error below:

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, OppUpdates: execution of AfterInsert caused by: System.DmlException: Update failed. First exception on row 0 with id 00k7000000U8CVpAAN; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, UniqueDelivID: execution of BeforeUpdate caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.UniqueDelivID: line 22, column 1: [] Trigger.OppUpdates: line 49, column 1: []
Stack Trace: Class.TestOppUpdates.TestOppUpdates: line 379, column 1


Does anyone know why I am getting this error?  Thanks.

Trigger (UniqueDelivID)
//Assigns a unique ID to each deliverable in every Opportunity so DyNad can track.
trigger UniqueDelivID on OpportunityLineItem (before insert, before update) {   

//if(checkRecursiveBI.runOnceBI()||checkRecursiveBU.runOnceBU())
//{
    Set<ID> setOliIds = new Set<ID>();
        for(OpportunityLineItem oli:Trigger.new){
            setOliIds.add(oli.Id);
        }
        Map<ID, OpportunityLineItem> mapOli = new Map<ID, OpportunityLineItem>([SELECT Id, Opportunity.Max_Deliv_Hx__c, Max_Deliv__c
                                                                                FROM OpportunityLineItem
                                                                                WHERE Id in:setOliIds]);
        if(mapOli.size()>0){

/*        List<OpportunityLineItem> oli1 = [SELECT Id, Max_Deliv__c
                                         FROM OpportunityLineItem
                                         WHERE Id IN: Trigger.newMap.keySet()]; 
                                     
            for (OpportunityLineItem oli :oli1){*/
            for(OpportunityLineItem oli1:Trigger.New){
                IF(mapOli.containsKey(oli1.Id) && (oli1.Max_Deliv__c == 0 || oli1.Max_Deliv__c == null)){
                    oli1.Max_Deliv__c = mapOli.get(oli1.Id).Opportunity.Max_Deliv_Hx__c + 1;
                }
            }
        }
//}

}

Test Class (TestOppUpdates)
// This class tests the trigger named OppUpdates.

@isTest(seeAllData=true)
public class TestOppUpdates {

    public static testMethod void TestOppUpdates() {       
                    
//Data Prep - Create Account, Opportunity, Product, etc.

        Account acct = TestCreateRecords.createAcct(0);
        insert acct;
        
    //Create Opportunity on Account
        Opportunity Opp = TestCreateRecords.createOpp(acct.Id);
       insert Opp;         
                       
    // Create Deliverables 

    List<product2> Insertprodlist= new list<product2>();

        //High-Risk Coaching
        Product2 deliv1 = new Product2 (name='Coaching-HR');
        deliv1.ProductCode = 'COACH_HR';
        deliv1.Product_Group__c = 'Coaching';
        Insertprodlist.add(deliv1);

        //Moderate-Risk Coaching
        Product2 deliv2 = new Product2 (name='Coaching-MR');
        deliv2.productcode = 'COACH_MR';
        deliv2.Product_Group__c = 'Coaching';
        Insertprodlist.add(deliv2);

        //Low-Risk Coaching
        Product2 deliv3 = new Product2 (name='Coaching-LR');
        deliv3.productcode = 'COACH_LR';
        deliv3.Product_Group__c = 'Coaching';
        Insertprodlist.add(deliv3);

        //Other Coaching
        Product2 deliv4 = new Product2 (name='Coaching-OTHER');
        deliv4.productcode = 'COACH_SELFREF';
        deliv4.Product_Group__c = 'Coaching';
        Insertprodlist.add(deliv4);

        //Weight Management
        Product2 deliv5 = new Product2 (name='Weight Management');
        deliv5.productcode = 'WEIGHTMGMTNODEVICE';
        deliv5.Product_Group__c = 'Weight Management';
        Insertprodlist.add(deliv5);

        //Tobacco Cessation
        Product2 deliv6 = new Product2 (name='Tobacco');
        deliv6.productcode = 'TOB_COACH';
        deliv6.Product_Group__c = 'Tobacco Cessation';
        Insertprodlist.add(deliv6);

        //Condition Management - Diabetes
        Product2 deliv7 = new Product2 (name='CM-Diabetes');
        deliv7.productcode = 'DIAB_COACH';
        deliv7.Product_Group__c = 'Condition Management';
        Insertprodlist.add(deliv7);

        //Condition Management - CHF
        Product2 deliv8 = new Product2 (name='CM-CHF');
        deliv8.productcode = 'HF_COACH';
        deliv8.Product_Group__c = 'Condition Management';
        Insertprodlist.add(deliv8);

        //Condition Management - CAD
        Product2 deliv9 = new Product2 (name='CM-CAD');
        deliv9.productcode = 'CAD_COACH';
        deliv9.Product_Group__c = 'Condition Management';
        Insertprodlist.add(deliv9);

        //Condition Management - COPD
        Product2 deliv10 = new Product2 (name='CM-COPD');
        deliv10.productcode = 'COPD_COACH';
        deliv10.Product_Group__c = 'Condition Management';
        Insertprodlist.add(deliv10);

        //Condition Management - Asthma
        Product2 deliv11 = new Product2 (name='CM-Asthma');
        deliv11.productcode = 'ASTH_COND_COACH';
        deliv11.Product_Group__c = 'Condition Management';
        Insertprodlist.add(deliv11);

        //Condition Management - Telephonic Bundle
        Product2 deliv12 = new Product2 (name='CM-Tel Bundle');
        deliv12.productcode = 'CMBUNDLE';
        deliv12.Product_Group__c = 'Condition Management';
        Insertprodlist.add(deliv12);

        //Health Concierge
        Product2 deliv13 = new Product2 (name='Health Concierge');
        deliv13.productcode = 'HCPLC_CGS';
        deliv13.Product_Group__c = 'Health Concierge';
        Insertprodlist.add(deliv13);
        
        //OWC
        Product2 deliv14 = new Product2 (name='Onsite Wellness Coordinators');
        deliv14.productcode = 'WELL_COORD';
        deliv14.Product_Group__c = 'Onsite Wellness Coordinators';
        Insertprodlist.add(deliv14);
        
        //Platform
        Product2 deliv15 = new Product2 (name='Core Package');
        deliv15.productcode = 'CORE_PKG';
        deliv15.Product_Group__c = 'Platform';
        Insertprodlist.add(deliv15);
        
        //Biometrics
        Product2 deliv16 = new Product2 (name='Biometrics');
        deliv16.productcode = 'BIOMETRIC_ONSITE';
        deliv16.Product_Group__c = 'Biometrics';
        Insertprodlist.add(deliv16);
        
        //Diabetes
        Product2 deliv17 = new Product2 (name='Diabetes');
        deliv17.productcode = 'DIAB_COACH';
        deliv17.Product_Group__c = 'Diabetes';
        Insertprodlist.add(deliv17);
        
        //Wellness Challenges
        Product2 deliv18 = new Product2 (name='Wellness Challenges');
        deliv18.productcode = 'WELLNESS';
        deliv18.Product_Group__c = 'Wellness Challenge';
        Insertprodlist.add(deliv18);
        
        //International - Platform
/*        Product2 deliv19 = new Product2 (name='International-Platform');
        deliv19.productcode = 'INT_PLAT';
        deliv19.Product_Group__c = 'International - Platform';
        Insertprodlist.add(deliv19);
        
        //International - Coaching
        Product2 deliv20 = new Product2 (name='International-Coaching');
        deliv20.productcode = 'INT_COACH';
        deliv20.Product_Group__c = 'International - Coaching';
        Insertprodlist.add(deliv20);*/
        
        insert Insertprodlist;
        
    // Get Pricebook
         Pricebook2 testpb = [select id from Pricebook2 where IsStandard = true];   
         
         List<PricebookEntry> InsertPricebookList= new List<PricebookEntry>();

// Add to pricebook
         PricebookEntry testdeliv1 = new PricebookEntry ();
         testdeliv1.pricebook2id = testpb.id;
         testdeliv1.product2id = deliv1.id;
         testdeliv1.IsActive = True;
         testdeliv1.UnitPrice = 10000;
         testdeliv1.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv1);
         
         PricebookEntry testdeliv2 = new PricebookEntry ();
         testdeliv2.pricebook2id = testpb.id;
         testdeliv2.product2id = deliv2.id;
         testdeliv2.IsActive = True;
         testdeliv2.UnitPrice = 10000;
         testdeliv2.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv2);
         
         PricebookEntry testdeliv3 = new PricebookEntry ();
         testdeliv3.pricebook2id = testpb.id;
         testdeliv3.product2id = deliv3.id;
         testdeliv3.IsActive = True;
         testdeliv3.UnitPrice = 10000;
         testdeliv3.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv3);
         
         PricebookEntry testdeliv4 = new PricebookEntry ();
         testdeliv4.pricebook2id = testpb.id;
         testdeliv4.product2id = deliv4.id;
         testdeliv4.IsActive = True;
         testdeliv4.UnitPrice = 10000;
         testdeliv4.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv4);
       
         PricebookEntry testdeliv5 = new PricebookEntry ();
         testdeliv5.pricebook2id = testpb.id;
         testdeliv5.product2id = deliv5.id;
         testdeliv5.IsActive = True;
         testdeliv5.UnitPrice = 10000;
         testdeliv5.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv5);
         
         PricebookEntry testdeliv6 = new PricebookEntry ();
         testdeliv6.pricebook2id = testpb.id;
         testdeliv6.product2id = deliv6.id;
         testdeliv6.IsActive = True;
         testdeliv6.UnitPrice = 10000;
         testdeliv6.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv6);
         
         PricebookEntry testdeliv7 = new PricebookEntry ();
         testdeliv7.pricebook2id = testpb.id;
         testdeliv7.product2id = deliv7.id;
         testdeliv7.IsActive = True;
         testdeliv7.UnitPrice = 10000;
         testdeliv7.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv7);
         
         PricebookEntry testdeliv8 = new PricebookEntry ();
         testdeliv8.pricebook2id = testpb.id;
         testdeliv8.product2id = deliv8.id;
         testdeliv8.IsActive = True;
         testdeliv8.UnitPrice = 10000;
         testdeliv8.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv8);
         
         PricebookEntry testdeliv9 = new PricebookEntry ();
         testdeliv9.pricebook2id = testpb.id;
         testdeliv9.product2id = deliv9.id;
         testdeliv9.IsActive = True;
         testdeliv9.UnitPrice = 10000;
         testdeliv9.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv9);
         
         PricebookEntry testdeliv10 = new PricebookEntry ();
         testdeliv10.pricebook2id = testpb.id;
         testdeliv10.product2id = deliv10.id;
         testdeliv10.IsActive = True;
         testdeliv10.UnitPrice = 10000;
         testdeliv10.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv10);
         
         PricebookEntry testdeliv11 = new PricebookEntry ();
         testdeliv11.pricebook2id = testpb.id;
         testdeliv11.product2id = deliv11.id;
         testdeliv11.IsActive = True;
         testdeliv11.UnitPrice = 10000;
         testdeliv11.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv11);
         
         PricebookEntry testdeliv12 = new PricebookEntry ();
         testdeliv12.pricebook2id = testpb.id;
         testdeliv12.product2id = deliv12.id;
         testdeliv12.IsActive = True;
         testdeliv12.UnitPrice = 10000;
         testdeliv12.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv12);
         
         PricebookEntry testdeliv13 = new PricebookEntry ();
         testdeliv13.pricebook2id = testpb.id;
         testdeliv13.product2id = deliv13.id;
         testdeliv13.IsActive = True;
         testdeliv13.UnitPrice = 10000;
         testdeliv13.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv13);
         
         PricebookEntry testdeliv14 = new PricebookEntry ();
         testdeliv14.pricebook2id = testpb.id;
         testdeliv14.product2id = deliv14.id;
         testdeliv14.IsActive = True;
         testdeliv14.UnitPrice = 10000;
         testdeliv14.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv14);
         
         PricebookEntry testdeliv15 = new PricebookEntry ();
         testdeliv15.pricebook2id = testpb.id;
         testdeliv15.product2id = deliv15.id;
         testdeliv15.IsActive = True;
         testdeliv15.UnitPrice = 10000;
         testdeliv15.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv15);
         
         PricebookEntry testdeliv16 = new PricebookEntry ();
         testdeliv16.pricebook2id = testpb.id;
         testdeliv16.product2id = deliv16.id;
         testdeliv16.IsActive = True;
         testdeliv16.UnitPrice = 10000;
         testdeliv16.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv16);
         
         PricebookEntry testdeliv17 = new PricebookEntry ();
         testdeliv17.pricebook2id = testpb.id;
         testdeliv17.product2id = deliv17.id;
         testdeliv17.IsActive = True;
         testdeliv17.UnitPrice = 10000;
         testdeliv17.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv17);
         
         PricebookEntry testdeliv18 = new PricebookEntry ();
         testdeliv18.pricebook2id = testpb.id;
         testdeliv18.product2id = deliv18.id;
         testdeliv18.IsActive = True;
         testdeliv18.UnitPrice = 10000;
         testdeliv18.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv18);
         
/*         PricebookEntry testdeliv19 = new PricebookEntry ();
         testdeliv19.pricebook2id = testpb.id;
         testdeliv19.product2id = deliv19.id;
         testdeliv19.IsActive = True;
         testdeliv19.UnitPrice = 10000;
         testdeliv19.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv19);
         
         PricebookEntry testdeliv20 = new PricebookEntry ();
         testdeliv20.pricebook2id = testpb.id;
         testdeliv20.product2id = deliv20.id;
         testdeliv20.IsActive = True;
         testdeliv20.UnitPrice = 10000;
         testdeliv20.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv20);*/

         Insert InsertPricebookList;
         

test.starttest();

        List<OpportunityLineItem> oli1 = new List<OpportunityLineItem>();
            integer todo = 20;
            for(integer bi=0; bi<todo; bi++) {
        
            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv1.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv2.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv3.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv4.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv5.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv6.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv7.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv8.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv9.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv10.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv11.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv12.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv13.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv14.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv15.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv16.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv17.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv18.id, OpportunityId = Opp.id) );

/*            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv19.id, OpportunityId = Opp.id, Prod_Grp__c = 'International - Platform') );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv20.id, OpportunityId = Opp.id, Prod_Grp__c = 'International - Coaching') );*/
         }
    
        insert oli1;
        
        delete oli1;

test.stoptest();
    }
}




  • July 25, 2014
  • Like
  • 0
Hello,

I have a trigger (see below) that works in my Sandbox and is covered by my test in my sandbox.  When I try to deploy to production, I get the error:

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, UniqueDelivID: execution of BeforeUpdate caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.UniqueDelivID: line 15, column 1: []

Can anyone help as to why I am getting this error?

Trigger:
//Assigns a unique ID to each deliverable in every Opportunity so DyNad can track.
trigger UniqueDelivID on OpportunityLineItem (before insert, before update) {   

    Set<ID> setOliIds = new Set<ID>();
        for(OpportunityLineItem oli:Trigger.new){
            setOliIds.add(oli.Id);
        }
        Map<ID, OpportunityLineItem> mapOli = new Map<ID, OpportunityLineItem>([SELECT Id, Opportunity.Max_Deliv_Hx__c, Max_Deliv__c
                                                                                FROM OpportunityLineItem
                                                                                WHERE Id in:setOliIds]);
        if(mapOli.size()>0){

            for(OpportunityLineItem oli1:Trigger.New){
                IF(mapOli.containsKey(oli1.Id) && oli1.Max_Deliv__c == null){
                    oli1.Max_Deliv__c = mapOli.get(oli1.Id).Opportunity.Max_Deliv_Hx__c + 1;
                }
            }
        }

}


  • July 23, 2014
  • Like
  • 0
Hello,

I have a trigger on a custom object (Client_Revenue__c).  When a record is created, edited, or deleted for this object, the trigger links the record of the current year (based on a field called Revenue_Year__c in the custom object) to a custom lookup field on the Account.  The test I created is only covering 25% of the trigger.  Lines 12 - 25 and 32-42 are not being covered.  Does anyone know why this would be happening?  Thanks,

Trigger:
trigger Contract2Account on Contract_Summary__c (after insert, after update, after delete) 
{          
    Try
    {
     Map<Id,Account> oppMap = new Map<Id,Account>();
     Set<id> Ids = new Set<id>();

if(trigger.isInsert || trigger.isUpdate)
{
    if(checkRecursiveAI.runOnceAI() || checkRecursiveAU.runOnceAU())
    {
        for (Contract_Summary__c prgm : Trigger.new){
            if(prgm.Type_of_Contract__c == 'Renewal' || prgm.Type_of_Contract__c == 'Initial MSA')
            Ids.add(prgm.Account_Name__c);
        }
     
        Map<id,Account> acctMap2 = new Map<id,Account>([Select Id,Name,Contract_Summary__c, Contract_Summary__r.Current_Effective_Date__c from Account Where Id in :Ids]);  
        for (Contract_Summary__c  prgm2 : Trigger.new){
            if(acctMap2.containsKey(prgm2.Account_Name__c) && (acctMap2.get(prgm2.Account_Name__c).Contract_summary__r.Current_Effective_Date__c < prgm2.Current_Effective_Date__c || acctMap2.get(prgm2.Account_Name__c).Contract_summary__r.Current_Effective_Date__c == null)) {
                Account a = acctMap2.get(prgm2.Account_Name__c);
                a.Contract_Summary__c = prgm2.Id;
                oppMap.put(a.id,a);
            }
        }
        update oppMap.values();
    }
}
     
if(trigger.isDelete)
{
    if(checkRecursiveAD.runOnceAD()){
        for (Contract_Summary__c prgm : Trigger.old){
            if(prgm.Type_of_Contract__c == 'Renewal' || prgm.Type_of_Contract__c == 'Initial MSA')
            Ids.add(prgm.Account_Name__c);
        }
        Map<id,Account> acctMap2 = new Map<id,Account>([Select Id,Name,Contract_Summary__c from Account Where Id in :Ids]);  
        for (Contract_Summary__c  prgm2 : Trigger.old){
                Account a = acctMap2.get(prgm2.Account_Name__c);
                a.Contract_Summary__c = null;
                oppMap.put(a.id,a);
        }
        update oppMap.values();
    }
}
    }
    catch(Exception e)
    {}
}

Test Class:

@isTest(SeeallData=true)
private class ContractSummary_Tests2 {

    private static testmethod void testSummary1() {

    Account a1 = new Account();
        a1.name = 'test';
        a1.Type = 'Employer';
    insert a1;
   
    Opportunity opp1 = new Opportunity();
            opp1.Name = 'Test Opportunity';
            opp1.StageName = 'Stage 6 - Live';
            opp1.CloseDate = date.newinstance(2020,1,31);
            opp1.Type = 'New Business';
            opp1.accountId=a1.Id;
        insert opp1;

    Opportunity opp2 = new Opportunity();
            opp2.Name = 'Test Opportunity';
            opp2.StageName = 'Stage 6 - Live';
            opp2.CloseDate = date.newinstance(2022,1,31);
            opp2.Type = 'Renewal';
            opp2.accountId=a1.Id;
        insert opp2;

    Contract_Summary__c testContSumm1 = new Contract_Summary__c ();
        testContSumm1.Related_Opportunity__c = opp1.Id;
        testContSumm1.Account_Name__c = opp1.Account.id;
        testContSumm1.Current_Effective_Date__c = date.newinstance(2020,1,31);
        testContSumm1.Current_Expiration_Date__c = date.newinstance(2022,1,31);
        testContSumm1.Type_of_Contract__c = 'Initial MSA';
        testContSumm1.Client_Signature_Date__c = date.newinstance(2020,1,31);
    insert testContSumm1;

    Contract_Summary__c testContSumm2= new Contract_Summary__c ();
        testContSumm2.Related_Opportunity__c = opp2.Id;
        testContSumm2.Account_Name__c = opp2.Account.id;
        testContSumm2.Current_Effective_Date__c = date.newinstance(2022,1,31);
        testContSumm2.Current_Expiration_Date__c = date.newinstance(2024,1,31);
        testContSumm2.Type_of_Contract__c = 'Renewal';
        testContSumm2.Client_Signature_Date__c = date.newinstance(2022,1,31);
    insert testContSumm2;

        
    Test.startTest();
    update opp1;
    update opp2;
    update testContSumm1;
    update testContSumm2;
    delete testContSumm2;
    Test.stopTest();

    }
}

Class to prevent infinite loops:
public Class checkRecursiveAI{
    private static boolean run = true;
    public static boolean runOnceAI(){
    if(run){
     run=false;
     return true;
    }
    else{
        return run;
    }
    }
}



  • July 21, 2014
  • Like
  • 0
Hello,

I have a custom object (Contract_Summary__c) that has a Master-Detail with Opportunity.  I have created a test class to test a trigger and I'm trying to populate the Account Name field on my Contract_Summary__c from the Opportunity field.  Can anyone give me the syntax to do this?  My code from the test class is below and Line 4 is where I'm having trouble:

public static Contract_Summary__c createContSumm(Id oppId){ 
        Contract_Summary__c ContSumm = new Contract_Summary__c();
            ContSumm.Related_Opportunity__c = oppId;
            ContSumm.Account_Name__c = oppId.AcctId.id;
            ContSumm.Current_Effective_Date__c = date.newinstance(2025,1,31);
            ContSumm.Current_Expiration_Date__c = date.newinstance(2027,1,31);
            ContSumm.Type_of_Contract__c = 'Initial MSA';
            ContSumm.Client_Signature_Date__c = date.newinstance(2025,1,31);
        return ContSumm;


  • July 21, 2014
  • Like
  • 0
Hello,

I have a custom object called Contract_Summary__c.  I have a trigger (below) which fires when a contract summary record is created, edited or delete, and updates a number of fields on the associated Opportunity based on the values in the custom object.  The trigger works as expected, but the test class I created (see below) only covers the Insert and Update functions of the trigger and not the Delete.  Lines 49-78 are not being covered.  Does anyone know why this happens or how to fix the test class to cover those lines?

Trigger:

trigger ContractUpdates on Contract_Summary__c (after insert, after update, after delete)
{

if(checkRecursiveBI.runOnceBI() || checkRecursiveBU.runOnceBU() || checkRecursiveBD.runOnceBD())
{
   
//Update Opportunity fields from values in Contract Summary object

    Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>();    
    set<Id> Ids = new Set <Id>(); 

    if(trigger.isInsert || trigger.isUpdate)
        {
    FOR(Contract_Summary__c con :trigger.new) {
        Ids.add(con.Related_Opportunity__c); 
    }
    system.debug('@@@@@Ids: '+Ids);
    Map<id,Opportunity> oppMap2 = new Map<id,Opportunity>([Select Id,Start_Date__c, End_Date__c from Opportunity Where Id in :Ids]); 
    system.debug('@@@@@oppMap2: '+oppMap2);
    system.debug('@@@@@Trigger.newMap.keySet(): '+Trigger.new);
    List<Contract_Summary__c> cs1 = [SELECT Id, Related_Opportunity__c,Current_Effective_Date__c, Current_Expiration_Date__c, Current_Term_Months__c, Auto_Renew_Notice_Days__c, Auto_Renew_Provision__c, Term_for_Convenience__c, Portal_SLAs__c, Coaching_Performance_Guarantees__c, Off_Shore_Resource_Restiction__c, Delegated_Entity_Agreement__c, Special_Terms__c
                                     FROM Contract_Summary__c
                                     WHERE Id IN: Trigger.new]; 
        
        
        for(Contract_Summary__c con :cs1) 
        {
            Opportunity o = oppMap2.get(con.Related_Opportunity__c);

            o.Start_Date__c = con.Current_Effective_Date__c;
            o.End_Date__c = con.Current_Expiration_Date__c;
            o.Current_Term_Months__c = con.Current_Term_Months__c;
            o.Auto_Renew__c = con.Auto_Renew_Provision__c;
            o.Auto_Renew_Notice_Days__c = con.Auto_Renew_Notice_Days__c;
            o.Term_for_Convenience__c = con.Term_for_Convenience__c;
            o.Portal_SLAs__c = con.Portal_SLAs__c;
            o.Coaching_Performance_Guarantees__c = con.Coaching_Performance_Guarantees__c;
            o.Off_Shore_Resource_Restiction__c = con.Off_Shore_Resource_Restiction__c;
            o.Delegated_Entity_Agreement__c = con.Delegated_Entity_Agreement__c;
            o.Special_Terms__c = con.Special_Terms__c;

            oppMap.put(o.id,o);
        }
            update oppMap.values();
        }

    IF(trigger.isDelete)
        {
    FOR(Contract_Summary__c con :trigger.old) {
        Ids.add(con.Related_Opportunity__c); 
    }
    
    Map<id,Opportunity> oppMap2 = new Map<id,Opportunity>([Select Id,Start_Date__c, End_Date__c from Opportunity Where Id in :Ids]); 

    List<Contract_Summary__c> cs2 = [SELECT Id,Related_Opportunity__c
                                     FROM Contract_Summary__c
                                     WHERE Id IN: Trigger.oldMap.keySet()]; 
        
        
        for(Contract_Summary__c con :cs2) 
        {
            Opportunity o = oppMap2.get(con.Related_Opportunity__c);

            o.Start_Date__c = null;
            o.End_Date__c = null;
            o.Current_Term_Months__c = null;
            o.Auto_Renew__c = FALSE;
            o.Auto_Renew_Notice_Days__c = null;
            o.Term_for_Convenience__c = FALSE;
            o.Portal_SLAs__c = FALSE;
            o.Coaching_Performance_Guarantees__c = FALSE;
            o.Off_Shore_Resource_Restiction__c = FALSE;
            o.Delegated_Entity_Agreement__c = FALSE;
            o.Special_Terms__c = FALSE;

            oppMap.put(o.id,o);
        }
            update oppMap.values();
        }
}

}

Test Class:

@isTest(SeeallData=true)
private class ContractSummary_Tests {

    private static testmethod void testSummary1() {

    Account a = [Select id, name, Type, Consultant_Partner_Primary__c FROM Account WHERE Type='Consultant/Broker' limit 1];
    Account a1 = new Account();
    a1.name ='test';
    a1.Consultant_Partner_Primary__c =a.id;
    insert a1;
   
    Opportunity opp = new Opportunity();
            opp.Name = 'Test Opportunity';
            opp.StageName = 'Stage 1 - Learn';
            opp.CloseDate = date.newinstance(2013,1,31);
            opp.Type = 'Renewal';
            opp.accountId=a1.id;
            opp.Consultant_Type__c = 'Primary Consultant';
            
        insert opp;
 a1.Consultant_Partner_Primary__c=a.Consultant_Partner_Primary__c;
 update a1;

        Contract_Summary__c testContSumm = TestContractCreate.createContSumm(opp.id);
        system.debug('@@@@testContSumm : '+testContSumm);
        insert testContSumm;

        Contract_Summary__c testContSumm2 = [SELECT id,Amendment_Number__c
                                             FROM Contract_Summary__c
                                             WHERE id =: testContSumm.Id];
        testContSumm2.Amendment_Number__c = 'Amendment #2';

        Contract_Summary__c testContSumm3 = TestContractCreate.createContSumm2(opp.id);
        system.debug('@@@@testContSumm3 : '+testContSumm3);
        insert testContSumm3;
        
    Test.startTest();
    update opp;
    update testContSumm2;
    delete testContSumm3;
    Test.stopTest();

    }
}



  • July 17, 2014
  • Like
  • 0
Hello,

I have a trigger that fires when a campaign is created and changes the default Member Status of Responded on the campaign to Registered, and also adds another status of Attended.  The trigger works well, but my test class is not covering line 19-26.  Does anyone know how I can get the test to cover these lines?

Trigger:
trigger CampaignMemberStatus on Campaign (after insert) {

if(checkRecursiveAI.runOnceAI())
{
   
    List<Campaign> newCamps = [select Id from Campaign where Id IN :trigger.new AND ParentID = Null];
    List<CampaignMemberStatus> cms = new List<CampaignMemberStatus>();
    Set<Id> camps = new Set<Id>();
    List<CampaignMemberStatus> cms2Delete = new List<CampaignMemberStatus>();
    List<CampaignMemberStatus> cms2Insert = new List<CampaignMemberStatus>();
   
    for(Campaign camp : newCamps){
      
            camps.add(camp.Id);
    }  
   
   
   for (CampaignMemberStatus cm: [Select Id, Label, CampaignID  FROM CampaignMemberStatus WHERE CampaignID IN :camps]){
      if(cm.Label == 'Responded' ){
            CampaignMemberStatus cms1 = new CampaignMemberStatus(CampaignId=cm.CampaignID, Label='Registered', HasResponded=false, IsDefault = False, SortOrder=4);          
            System.debug(cms1);
            cms2Delete.add(cm);
            cms2Insert.add(cms1);
           
            CampaignMemberStatus cms3 = new CampaignMemberStatus(CampaignId = cm.CampaignId, HasResponded=true, Label = 'Attended', SortOrder = 5);
            cms2Insert.add(cms3);

      }

    }
    //perform insert before delete because system requires at least one CMS for a Campaign
    insert cms2Insert;
    delete cms2Delete;

}

}

Test Class:

@isTest private class CampaignMembStatus{

    @isTest private static void test_Memb_Status() {
    
        Campaign camp=new Campaign(Name='Test Campaign',IsActive=True);
        insert camp;

    Test.StartTest();
    Test.StopTest();
        
    }
}


  • July 16, 2014
  • Like
  • 0
Hello,

I have a trigger the queries the OpportunityLineItem records on an Opportunity, looks for certain product families, and then updates the Opportunity record with the roll-up amount from each family and checks a box if that family is represented in the OpportunityLineItems.  The trigger works fine.  The test below covers 54% of the trigger, but what it is not covering is everything in the trigger after the line "IF(trigger.isdelete){".  I didn't post the trigger because it is very large.  Does anyone know why the "delete oli1;" line (line 94) in the test class below would not cover the delete portion of the trigger and how to fix it?  Thanks!

// This class tests the trigger named OppUpdates.

@isTest(seeAllData=true)
private class TestOppUpdates {

    static testMethod void TestOppUpdates() {       
                    
//Data Prep - Create Account, Opportunity, Product, etc.

        Account acct = new Account(name='Test Account', Type = 'Employer');
        insert acct;
        
    //Create Opportunity on Account
        Opportunity Opp = new Opportunity(Name='Test Account - New Opp1');
        Opp.StageName = 'Stage 1 - Learn';
        Opp.CloseDate = Date.today();
        Opp.AccountId = acct.id;
        insert Opp;         
                       
    // Create Deliverables 

    List<product2> Insertprodlist= new list<product2>();

        //High-Risk Coaching
        Product2 deliv1 = new Product2 (name='Coaching-HR');
        deliv1.ProductCode = 'COACH_HR';
        deliv1.Product_Group__c = 'Coaching';
        Insertprodlist.add(deliv1);

        //Moderate-Risk Coaching
        Product2 deliv2 = new Product2 (name='Coaching-MR');
        deliv2.productcode = 'COACH_MR';
        deliv2.Product_Group__c = 'Coaching';
        Insertprodlist.add(deliv2);

        //Low-Risk Coaching
        Product2 deliv3 = new Product2 (name='Coaching-LR');
        deliv3.productcode = 'COACH_LR';
        deliv3.Product_Group__c = 'Coaching';
        Insertprodlist.add(deliv3);

        
        insert Insertprodlist;
        
    // Get Pricebook
         Pricebook2 testpb = [select id from Pricebook2 where IsStandard = true];   
         
         List<PricebookEntry> InsertPricebookList= new List<PricebookEntry>();

// Add to pricebook
         PricebookEntry testdeliv1 = new PricebookEntry ();
         testdeliv1.pricebook2id = testpb.id;
         testdeliv1.product2id = deliv1.id;
         testdeliv1.IsActive = True;
         testdeliv1.UnitPrice = 10000;
         testdeliv1.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv1);
         
         PricebookEntry testdeliv2 = new PricebookEntry ();
         testdeliv2.pricebook2id = testpb.id;
         testdeliv2.product2id = deliv2.id;
         testdeliv2.IsActive = True;
         testdeliv2.UnitPrice = 10000;
         testdeliv2.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv2);
         
         PricebookEntry testdeliv3 = new PricebookEntry ();
         testdeliv3.pricebook2id = testpb.id;
         testdeliv3.product2id = deliv3.id;
         testdeliv3.IsActive = True;
         testdeliv3.UnitPrice = 10000;
         testdeliv3.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv3);

         Insert InsertPricebookList;
         

test.starttest();
        List<OpportunityLineItem> oli1 = new List<OpportunityLineItem>();
            integer todo = 20;
            for(integer bi=0; bi<todo; bi++) {
        
            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv1.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv2.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv3.id, OpportunityId = Opp.id) );
         }
        insert oli1;
        
        delete oli1;
        
test.stoptest();
    }
}


  • July 16, 2014
  • Like
  • 0
Hello,

I have a trigger that queries LineItems on an Opportunity and updates the Opportunity with counts.  The test class below returns coverage of 54% and is not covering deletion of line items.  I have a delete statement on line 78 that I thought would work, but is there something else I need to do?

Test Class:
// This class tests the trigger named OppUpdates.

@isTest(seeAllData=true)
private class TestOppUpdates {

    static testMethod void TestOppUpdates() {       
                    
//Data Prep - Create Account, Opportunity, Product, etc.

        Account acct = new Account(name='Test Account', Type = 'Employer');
        insert acct;
        
    //Create Opportunity on Account
        Opportunity Opp = new Opportunity(Name='Test Account - New Opp1');
        Opp.StageName = 'Stage 1 - Learn';
        Opp.CloseDate = Date.today();
        Opp.AccountId = acct.id;
        insert Opp;         
                       
    // Create Deliverables 

    List<product2> Insertprodlist= new list<product2>();

        //High-Risk
        Product2 deliv1 = new Product2 (name='HR');
        deliv1.ProductCode = 'COACH_HR';
        deliv1.Product_Group__c = 'HR';
        Insertprodlist.add(deliv1);

        //Moderate-Risk
        Product2 deliv2 = new Product2 (name='MR');
        deliv2.productcode = 'COACH_MR';
        deliv2.Product_Group__c = 'MR';
        Insertprodlist.add(deliv2);

        
        insert Insertprodlist;
        
    // Get Pricebook
         Pricebook2 testpb = [select id from Pricebook2 where IsStandard = true];   
         
         List<PricebookEntry> InsertPricebookList= new List<PricebookEntry>();

// Add to pricebook
         PricebookEntry testdeliv1 = new PricebookEntry ();
         testdeliv1.pricebook2id = testpb.id;
         testdeliv1.product2id = deliv1.id;
         testdeliv1.IsActive = True;
         testdeliv1.UnitPrice = 10000;
         testdeliv1.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv1);
         
         PricebookEntry testdeliv2 = new PricebookEntry ();
         testdeliv2.pricebook2id = testpb.id;
         testdeliv2.product2id = deliv2.id;
         testdeliv2.IsActive = True;
         testdeliv2.UnitPrice = 10000;
         testdeliv2.UseStandardPrice = false;
         InsertPricebookList.add(testdeliv2);
         
         Insert InsertPricebookList;
         

test.starttest();
        List<OpportunityLineItem> oli1 = new List<OpportunityLineItem>();
       // integer todo = 300;
       integer todo = 20;
        for(integer bi=0; bi<todo; bi++) {
            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv1.id, OpportunityId = Opp.id) );

            oli1.add( new OpportunityLineItem(Quantity = 1, TotalPrice = 10000, 
            PriceBookEntryId = testdeliv2.id, OpportunityId = Opp.id) );
         }
    
      insert oli1;  
   
      delete oli1; 
        
        test.stoptest();

    }
}


  • July 11, 2014
  • Like
  • 0