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

Test class not covering code

Hi,

My class compares old and new values of records in one of the for loops.
I am getting only 17% code coverage for the class. Below is my apex class and test class.


Apex Class :
 
public class nmPGAllSemFee
{   
    public string query{get;set;}
    public void createNextSemOpportunityOnClosedWonForFullFee(List<Opportunity> triggerNew, map<id, Opportunity> oldMap)
    {
        List<Opportunity> opptyListToInsert = new List<Opportunity>();
        List<nm_Payment__c> paymentListToInsert = new List<nm_Payment__c>();
        
        for(Opportunity newOpportunity : triggerNew)
        {
            Id opptyId = newOpportunity.Id;
            
            
            Opportunity oldOpportunity =  oldMap.get(opptyId);
            System.debug('!!!!!newOpportunity!!!' + newOpportunity);
            if(newOpportunity.nm_Fee_Type__c == 'PGAllSemFee' && 
                newOpportunity.nm_Future_Sems_Created__c == false && 
                newOpportunity.StageName != oldOpportunity.StageName &&  
                newOpportunity.StageName == 'Closed Won'){
                
                opptyListToInsert = new List<Opportunity>();
                newOpportunity.nm_Future_Sems_Created__c = true;
                Opportunity sem2Opp = getNextSemOpportunity(newOpportunity);
                Opportunity sem3Opp = getNextSemOpportunity(sem2Opp);
                Opportunity sem4Opp = getNextSemOpportunity(sem3Opp);
                
                opptyListToInsert.add(sem2Opp);
                opptyListToInsert.add(sem3Opp);
                opptyListToInsert.add(sem4Opp);
                
                insert opptyListToInsert;
                system.debug('!!!!!opptyListToInsert!!!!!!'+opptyListToInsert);
                nm_Payment__c existingPaymentObj = getPaymentForOpportunity(newOpportunity.Id);
                
                nm_Payment__c sem2Payment = existingPaymentObj.clone();
                sem2Payment.nm_OpportunityNew__c = sem2Opp.Id;
                nm_Payment__c sem3Payment = existingPaymentObj.clone();
                sem3Payment.nm_OpportunityNew__c = sem3Opp.Id;
                nm_Payment__c sem4Payment = existingPaymentObj.clone();
                sem4Payment.nm_OpportunityNew__c = sem4Opp.Id;

                paymentListToInsert.add(sem2Payment);
                paymentListToInsert.add(sem3Payment);
                paymentListToInsert.add(sem4Payment);
                
                insert paymentListToInsert;
                
            }
            
        }
        
        }

    public nm_Payment__c getPaymentForOpportunity(Id id){
            List<nm_Payment__c> paymentList = new List<nm_Payment__c>();
            String SobjectApiName = 'nm_Payment__c';
            Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
            Map<String, Schema.SObjectField> fieldMap = schemaMap.get(SobjectApiName).getDescribe().fields.getMap();
 
            String commaSepratedFields = '';
            for(String fieldName : fieldMap.keyset()){
                if(commaSepratedFields == null || commaSepratedFields == ''){
                    commaSepratedFields = fieldName;
                }else{
                    commaSepratedFields = commaSepratedFields + ', ' + fieldName;
                }
            }
            
            query = 'select ' + commaSepratedFields + ' from ' + SobjectApiName + ' where nm_OpportunityNew__c = \''+ id + '\' AND nm_PaymentType__c = \'Admission\' AND nm_PaymentStatus__c = \'Payment Approved\'';
            system.debug('!!!!!!!query!!!!!!!'+query);
            paymentList = Database.query(query);
            system.debug('!!!!!!!paymentList!!!!!!!'+paymentList);
            return paymentList[0];
    }
    
    public Opportunity getNextSemOpportunity(Opportunity currentSemOpportunity){
        
        Opportunity nextSemOpportunity = currentSemOpportunity.clone();
        if(currentSemOpportunity.nm_Session__c == 'January'){
            nextSemOpportunity.nm_Session__c = 'July';
        }else if(currentSemOpportunity.nm_Session__c == 'July'){
            nextSemOpportunity.nm_Session__c = 'January';
            nextSemOpportunity.nm_Year__c = currentSemOpportunity.nm_Year__c + 1;
        }
        
        Integer nextSem = Integer.valueOf(currentSemOpportunity.nm_Semester__c ) + 1;
        nextSemOpportunity.StageName = 'Closed Won - Re-registration Pending';
        nextSemOpportunity.nm_Fee_Type__c = 'PGAllSemFee-Considered';//Changing so that trigger does not fire again and future Opportunities are not further created
        nextSemOpportunity.nm_Semester__c = String.valueOf(nextSem);
        return nextSemOpportunity;
    }

}
Test Class :
 
@isTest
public class nmPGAllSemFeeTracker
{
    public static  Opportunity objOpp;
    public static  Opportunity objOpp2;
    public static  nm_Payment__c objPayment;
    public static Lead objLead;
    public static List<Opportunity> opps;
    static  testmethod  void unitTestForPGAllSemFee()
    {
        Product2 objProduct = new Product2();
        objProduct = CommonTrackerClass.createProduct(objProduct);
        Pricebook2 objpriceBook;
        objpriceBook =CommonTrackerClass.createPricebook();
        PricebookEntry objPBE;
        string strrecord = [select id from RecordType where SobjectType='Account' AND IsPersonType=True limit 1].id;
        Account Acc = new Account(
        RecordTypeID=strrecord,
        FirstName='jane',
        LastName='doe',
        nm_PreStudentNo__c ='77213',
        nm_StudentStatus__c='Confirmed',
        nm_Tagged_Pricebook__c=objpriceBook.id,
        nm_SerialNo__c=2,
        PersonMobilePhone='8377985721',
        PersonEmail='teste@gmail.com') ; 
        Test.startTest();
        insert Acc;          
        objOpp = new Opportunity();
        objOpp.StageName = 'Closed';
        objOpp.nm_Fee_Type__c = 'PGAllSemFee';
        objOpp.nm_Future_Sems_Created__c = false;  
        objOpp.Accountid = Acc.id;
        objOpp.CloseDate = date.parse('06/27/2015');
        objOpp.Name = 'testOpp';
        opps = new List<Opportunity>();
        opps.add(objOpp);
        
        objOpp2 = new Opportunity();
        objOpp2.StageName = 'Closed Won';
        objOpp2.nm_Fee_Type__c = 'PGAllSemFee';
        objOpp2.nm_Future_Sems_Created__c = false;  
        objOpp2.Accountid = Acc.id;
        objOpp2.CloseDate = date.parse('06/27/2015');
        objOpp2.Name = 'testOpp2';
        opps.add(objOpp2);
        insert opps;
        update opps;
        //objOpp = CommonTrackerClass.createOpportunity(objOpp);
        
        //objOpp = [Select StageName from Opportunity where Id =: objOpp.Id];
        //objOpp.StageName = 'Closed Won';
        //update objOpp;
        
        //objPBE =CommonTrackerClass.CreatePriceBookEntry(objProduct.id,objpriceBook.id);
        //nm_StudentProgram__c objSp;
       // objSp=CommonTrackerClass.createStudentProgram(objSp);
        
         objLead = new  Lead();
         objLead.nm_SelectedIC__c ='1';
         objLead.LastName ='kumar';
         objLead.FirstName='amit';
         objLead.nm_DateOfBirth__c =System.today();
         objLead.status='Hot';
         objLead.Email='mayurnagaonkar@gmail.com';
         objLead.MobilePhone ='8377985721';
         objLead.nm_ChooseaProgram__c ='Certificate Programs';
         //objLead.nm_Program__c = objP.Id;
         //objLead.nm_EligiblityCriteria__c = objEc.Id;
         objLead.nm_PaymentCompleted__c = false;
         objLead.nm_SelectedProgram__c ='MCA';
         //objLead.nm_InformationCenter__c =objCenter1.id;
         objLead.nm_Year__c =2014;
         objLead.LeadSource ='Walk -in';
         objLead.nm_PaymentStatus__c ='Registration form filled';
         objLead.nm_PlantoStart__c ='2-4 Months';
         objLead.nm_Session__c='July';
         objLead.nm_CopyAddress__c='Yes';
         objLead.nm_ModeOfPayment__c='Online';
         objLead.nm_EscallationDone__c=8;
         objLead.nm_RegistrationID__c='a0BN0000001FUdB';
         //objLead.nm_RegistrationNo__c='a0BN0000001FUdB';
         insert objLead;
        
        objPayment = new nm_Payment__c();
        objPayment.nm_OpportunityNew__c =objOpp.id;
        objPayment.nm_Lead__c=objLead.id;
        objPayment.nm_PaymentType__c ='Admission';
        objPayment.nm_Amount__c = 15500;
        objPayment.nm_PaymentStatus__c ='Payment Approved';
        objPayment = CommonTrackerClass.createPayment(objPayment);
        
        nmPGAllSemFee controller=new nmPGAllSemFee();
        //Apexpages.StandardController stdController = new Apexpages.StandardController(objOpp.Id);
        List<Opportunity> lstOpp = [Select Id, Name from Opportunity where Id =: objOpp.Id];
        if(lstOpp.size() > 0){
        controller.getPaymentForOpportunity(lstOpp[0].Id);
        }
        Test.stopTest();

    }

}
Can you please help me in increasing the code coverage

Thanks
 
SaranSaran
Hi,


You are inserting the opportunity and updating it the same way. But in the class it will fail in the IF condition. You have check with old values.
newOpportunity.StageName != oldOpportunity.StageName 

So you have create a opportunity with any other stageName 
objOpp = new Opportunity();
objOpp.StageName = 'Prospect';
objOpp.nm_Fee_Type__c = 'PGAllSemFee';
objOpp.nm_Future_Sems_Created__c = false;  
objOpp.Accountid = Acc.id;
objOpp.CloseDate = date.parse('06/27/2015');
objOpp.Name = 'testOpp';
insert objOpp;

Opportunity updateOpp = new opportunity();
updateOpp = [select id, stageName from opportunity where id =: objOpp.Id];
updateOpp.StageName = 'Closed Won';
update updateOpp;

So that it will satisfy the IF condition and you may get the coverage increased

Thanks
 
sfdc18sfdc18
Hi Saraz,

The code is called through before update trigger.
So it is not allowing your code.
Is there any other alternative.

Thanks
SaranSaran
What you mean by not allowing is it showing any errors??
sfdc18sfdc18
Yes....you cannot update in before update trigger
Amit Chaudhary 8Amit Chaudhary 8
Please try below code. I hope that will help you.
@isTest
public class nmPGAllSemFeeTracker
{
    public static  Opportunity objOpp;
    public static  Opportunity objOpp2;
    public static  nm_Payment__c objPayment;
    public static Lead objLead;
    public static List<Opportunity> opps;
    static  testmethod  void unitTestForPGAllSemFee()
    {
        Product2 objProduct = new Product2();
        objProduct = CommonTrackerClass.createProduct(objProduct);
        Pricebook2 objpriceBook;
        objpriceBook =CommonTrackerClass.createPricebook();
        PricebookEntry objPBE;
        string strrecord = [select id from RecordType where SobjectType='Account' AND IsPersonType=True limit 1].id;
        Account Acc = new Account(
        RecordTypeID=strrecord,
        FirstName='jane',
        LastName='doe',
        nm_PreStudentNo__c ='77213',
        nm_StudentStatus__c='Confirmed',
        nm_Tagged_Pricebook__c=objpriceBook.id,
        nm_SerialNo__c=2,
        PersonMobilePhone='8377985721',
        PersonEmail='teste@gmail.com') ; 
		
        Test.startTest();
        insert Acc;          
		
        objOpp = new Opportunity();
        objOpp.StageName = 'Open'; // Please add valid status
        objOpp.nm_Fee_Type__c = 'PGAllSemFee';
        objOpp.nm_Future_Sems_Created__c = false;  
        objOpp.Accountid = Acc.id;
        objOpp.CloseDate = date.parse('06/27/2015');
        objOpp.Name = 'testOpp';
		insert 	objOpp;
		
        objOpp.StageName = 'Closed Won';
		
        update objOpp;
        
        Test.stopTest();

    }

}

Please check below blog for more information on test classes :-
http://amitsalesforce.blogspot.in/2015/06/best-practice-for-test-classes-sample.html


Please lst us know if this will help you.

Thanks,
Amit Chaudhary
sfdc18sfdc18
Hi Amit,

It gives error.
CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, : execution ofBeforeUpdate.

Thanks