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
Swaroopa Akula 10Swaroopa Akula 10 

Test apex class - Code coverage

I have a trigger and i am trying to create a test class. But not sure how to write test class to fulfill the test coding coverage for test apex class


TRIGGER:



trigger opportunitytrigger on opportunity(after update){
    Set<Id> oppIds = new Set<Id>();
   // Set<Id> oppWithContractAgreement = new Set<Id>();
     List<APXT_Redlining__Contract_Agreement__c> oppWithContractAgreement = new List<APXT_Redlining__Contract_Agreement__c>();
     List<Opportunity> opportunity = new List<Opportunity>();
     
    for(opportunity opp:Trigger.new)
    {
        if(opp.Stagename=='Closed Won')
        {
            oppIds.add(opp.id);
            opportunity.add(opp);

        }

    }

List<APXT_Redlining__Contract_Agreement__c> con =[Select Id, Opportunity__c,APXT_Redlining__Status__c,Verified_Signed_IO__c from APXT_Redlining__Contract_Agreement__c  where Opportunity__c IN :oppIds];
    
    {
     if(con.size()>0)
     system.debug(+con.size());
      
      {
          for(APXT_Redlining__Contract_Agreement__c c :con)
          
          {
          if( c.APXT_Redlining__Status__c == 'Active' && c.Verified_Signed_IO__c ==FALSE){
            oppWithContractAgreement.add(c);
            system.debug('-----------'+oppWithContractAgreement.size());
            }
}
      }
    }

 For(Opportunity opps:opportunity)
 {
    if(oppWithContractAgreement.size()>0)
    {
        system.debug(oppWithContractAgreement.size());
        opps.addError('Closed Won Opportunity must need to have active contract agreement and customer signed date captured or Closed Won Opportunity must need to have active contract agreement');
    }
    
    if(con.size()==0)
    {
        opps.addError('Closed Won Opportunity must need to have contract agreement' );
    }
    
 }

}


TEST CLASS:

@isTest
private class OpportunityTriggerHandler1_Test {
    
    @isTest static void testCreateOpportunityTarget() {
        
        //create Account
        Account acc = new Account();
        acc.Name = 'Test Account';
        insert acc;
        
        
        Test.startTest();
        
        Opportunity opp = new Opportunity();
        opp.AccountId = acc.Id;
        opp.Name = 'Test Opportunity';
        opp.StageName = 'Closed Won';
        opp.CloseDate = Date.Today().addDays(20);
        insert opp;
        
        Test.stopTest();
        
        List<APXT_Redlining__Contract_Agreement__c> CA = new List<APXT_Redlining__Contract_Agreement__c>();
        CA = [Select Id, Opportunity__c,APXT_Redlining__Status__c,Verified_Signed_IO__c from APXT_Redlining__Contract_Agreement__c ];

        System.assert(CA[0].Opportunity__c == opp.Id); 
    }      
}
Abdul KhatriAbdul Khatri
Hi Swaroopa

I review your code and found issues so fixed them in my code below with the test class 100% coverage. Please take a look on the code, compare it with yours and see the changes.

I see you are only running the trigger after update, are you also looking for after insert?

I have cover the test keeping the same context, I think the code should also work for after insert
trigger Opportunitytrigger on opportunity(after update){
    Map<Id, APXT_Redlining__Contract_Agreement__c> idOppApxtredlcontractMap = new Map<Id, APXT_Redlining__Contract_Agreement__c>();
    Map<Id, Opportunity> opportunityMap = new Map<Id, Opportunity>();
    
    for(opportunity opp:Trigger.new){

        if(opp.Stagename=='Closed Won')
        {
            opportunityMap.put(opp.Id, opp);    
        }
        
    }
    
    if(!opportunityMap.isEmpty()) 
    {
        
        List<APXT_Redlining__Contract_Agreement__c> con = [Select Id, Opportunity__c,APXT_Redlining__Status__c,Verified_Signed_IO__c from APXT_Redlining__Contract_Agreement__c  where Opportunity__c IN : opportunityMap.keyset()];
        
        for(Contract_Agreement__c c : con)
            
        {
            if(c.APXT_Redlining__Status__c == 'Active' && c.Verified_Signed_IO__c == FALSE){
				idOppApxtredlcontractMap.put(c.opportunity__c, c);                
            }
        }
        
        for(Opportunity opps : opportunityMap.values())
        {
            if(idOppApxtredlcontractMap != null && idOppApxtredlcontractMap.get(opps.Id) != null)
            {
                system.debug(idOppApxtredlcontractMap.get(opps.Id));
                opps.addError('Closed Won Opportunity must need to have active contract agreement and customer signed date captured or Closed Won Opportunity must need to have active contract agreement');
            }else{
                opps.addError('Closed Won Opportunity must need to have contract agreement' );
            }
            
        }
    }
}

test class
@isTest
private class OpportunityTriggerHandler1_Test {

    @isTest static void testCreateOpportunityTarget() {
        
        //create Account
        Account acc = new Account();
        acc.Name = 'Test Account';
        insert acc;
                
        Opportunity opp = new Opportunity();
        opp.AccountId = acc.Id;
        opp.Name = 'Test Opportunity';
        opp.StageName = 'New';
        opp.CloseDate = Date.Today().addDays(20);
        insert opp;

        Test.startTest();
        try {
            opp.StageName = 'Closed Won';
            update opp;
        } catch (Exception ex){
            Assert.isTrue(ex.getMessage().contains('Closed Won Opportunity must need to have contract agreement'));
        }
        Test.stopTest();

    } 
    
    
    @isTest static void testCreateOpportunityTargetWithAgreement() {
        
        //create Account
        Account acc = new Account();
        acc.Name = 'Test Account';
        insert acc;
                
        Opportunity opp = new Opportunity();
        opp.AccountId = acc.Id;
        opp.Name = 'Test Opportunity';
        opp.StageName = 'New';
        opp.CloseDate = Date.Today().addDays(20);
        insert opp;
        
        APXT_Redlining__Contract_Agreement__c caAgreement = new APXT_Redlining__Contract_Agreement__c();
        caAgreement.APXT_Redlining__Status__c = 'Active';
        caAgreement.Opportunity__c = opp.Id;
        insert caAgreement;

        Test.startTest();
        try {
            opp.StageName = 'Closed Won';
            update opp;
        } catch (Exception ex){
            Assert.isTrue(ex.getMessage().contains('Closed Won Opportunity must need to have active contract agreement and customer signed date captured or Closed Won Opportunity must need to have active contract agreement'));
        }
        Test.stopTest();
        
    }      

}


Regards,
Abdul Aziz Khatri
Prateek Prasoon 25Prateek Prasoon 25
@isTest
private class OpportunityTriggerTest {
    @isTest
    static void testOpportunityTrigger() {
        // Create test data
        Opportunity opp = new Opportunity(
            Name = 'Test Opportunity',
            StageName = 'Prospecting'
        );
        insert opp;
        
        APXT_Redlining__Contract_Agreement__c contract = new APXT_Redlining__Contract_Agreement__c(
            Opportunity__c = opp.Id,
            APXT_Redlining__Status__c = 'Active',
            Verified_Signed_IO__c = false
        );
        insert contract;
        
        // Trigger the update event
        Test.startTest();
        opp.StageName = 'Closed Won';
        update opp;
        Test.stopTest();
        
        // Verify the error messages
        System.assertEquals(1, opp.getErrors().size(), 'Expected one error message');
        System.assertEquals('Closed Won Opportunity must need to have active contract agreement and customer signed date captured or Closed Won Opportunity must need to have active contract agreement', opp.getErrors()[0].getMessage());
    }
}

If you find my answer helpful, please mark it as the best answer. Thanks!
SubratSubrat (Salesforce Developers) 
Hello Swaroopa ,

The test class you provided only tests the creation of an Opportunity and verifies that a related Contract Agreement record is created. However, it does not provide full coverage for the Opportunity trigger. To achieve full coverage, you need to write additional test methods that cover different scenarios and conditions within the trigger.

Please check with the below code and let me know further :
 
@isTest
private class OpportunityTriggerHandler1_Test {
    
    @isTest
    static void testClosedWonOpportunityWithActiveContractAgreement() {
        try {
            // Create an Account
            Account acc = new Account();
            acc.Name = 'Test Account';
            insert acc;
            
            // Create a Contract Agreement
            APXT_Redlining_Contract_Agreementc agreement = new APXT_RedliningContract_Agreement_c();
            agreement.Opportunity__c = null; // Set it to null to simulate an inactive agreement
            agreement.APXT_Redlining_Status_c = 'Inactive';
            agreement.Verified_Signed_IO__c = false;
            insert agreement;
            
            Test.startTest();
            
            // Create a Closed Won Opportunity
            Opportunity opp = new Opportunity();
            opp.AccountId = acc.Id;
            opp.Name = 'Test Opportunity';
            opp.StageName = 'Closed Won';
            opp.CloseDate = Date.Today().addDays(20);
            insert opp;
            
            Test.stopTest();
            
            // Verify that the Opportunity has an error message
            opp = [SELECT Id, Name, StageName FROM Opportunity WHERE Id = :opp.Id];
            System.assertEquals('Closed Won Opportunity must need to have active contract agreement and customer signed date captured or Closed Won Opportunity must need to have active contract agreement', opp.StageName);
        } catch (Exception e) {
            System.assert(false, 'An exception occurred: ' + e.getMessage());
        }
    }   
    
    @isTest
    static void testClosedWonOpportunityWithoutContractAgreement() {
        try {
            // Create an Account
            Account acc = new Account();
            acc.Name = 'Test Account';
            insert acc;
            
            Test.startTest();
            
            // Create a Closed Won Opportunity
            Opportunity opp = new Opportunity();
            opp.AccountId = acc.Id;
            opp.Name = 'Test Opportunity';
            opp.StageName = 'Closed Won';
            opp.CloseDate = Date.Today().addDays(20);
            insert opp;
            
            Test.stopTest();
            
            // Verify that the Opportunity has an error message
            opp = [SELECT Id, Name, StageName FROM Opportunity WHERE Id = :opp.Id];
            System.assertEquals('Closed Won Opportunity must need to have contract agreement', opp.StageName);
        } catch (Exception e) {
            System.assert(false, 'An exception occurred: ' + e.getMessage());
        }
    }
}

If this helps , please mark this as Best Answer.
Thank you.
Arun Kumar 1141Arun Kumar 1141

Hi Swaroopa,

1. Trigger Class: (Code Coverage 100%)

User-added image

2. Test Class:
 
@IsTest
public class OpportunityTriggerTest {
    @IsTest
    static void testOpportunityTrigger() {
        Account testAccount = new Account(Name = 'Test Account');
        insert testAccount;
        
        Opportunity testOpportunity = new Opportunity(Name = 'Test Opportunity', StageName = 'Closed Lost', AccountId = testAccount.Id, CloseDate = Date.today());
        insert testOpportunity;
        
        testOpportunity.StageName = 'Closed Won';
        Database.SaveResult result = Database.update(testOpportunity, false);
        
        System.assertEquals(false, result.isSuccess());
        System.assertEquals(1, result.getErrors().size());
        System.assertEquals('Closed Won Opportunity must have a contract agreement.', result.getErrors()[0].getMessage());
        
        APXT_Redlining_Contract_Agreement__c testContractAgreement = new APXT_Redlining_Contract_Agreement__c(Opportunity__c = testOpportunity.Id, APXT_Redlining_Status__c = 'Active', Verified_Signed_IO__c = false);
        insert testContractAgreement;
        
        testOpportunity.StageName = 'Closed Won';
        Database.SaveResult resultNew = Database.update(testOpportunity, false);
        
        System.assertEquals(false, resultNew.isSuccess());   
        System.assertEquals(1, resultNew.getErrors().size());
        System.assertEquals('Closed Won Opportunity must have an active contract agreement and customer-signed date captured.', resultNew.getErrors()[0].getMessage());
    }
}

Hope this will be helpful.
Thanks!