+ Start a Discussion
Abc234Abc234 

How to increase Code coverage

Apex Controller:
=====================

public with sharing class ApexButtonGetDist{
    public static Opportunity theOpportunity = new Opportunity();
    public static Opportunity theOpportunity2 = new Opportunity();
    public static Account getDistributor = new Account();
    
    public ApexButtonGetDist(ApexPages.StandardController stdController){
       theOpportunity = (Opportunity)stdController.getRecord();  
    }
    
    public PageReference doMyApexLogic() {
        theOpportunity2 = [SELECT ID, Name, Distributor_Name__c,Dist_street__c,Dist_City__c,Dist_State__c,Dist_PostalCode__c from Opportunity where Id = :theOpportunity.Id];
        getDistributor = [SELECT ID, Name, BillingStreet,BillingState,BillingCity,BillingPostalCode,SourceCode__c from Account where Id = :theOpportunity2.Distributor_Name__c];
        theOpportunity.Dist_street__c = getDistributor.BillingStreet;
      theOpportunity.Dist_City__c = getDistributor.BillingCity;
      theOpportunity.Dist_State__c = getDistributor.BillingState;
      theOpportunity.Dist_PostalCode__c = getDistributor.BillingPostalCode;        
      theOpportunity.Distr_SourceCode__c = getDistributor.SourceCode__c;        
        update theOpportunity;
        return new PageReference('/' + theOpportunity.ID);
    }
}

Test Class
@isTest
private class ApexButtonGetDistTest {
      
        static testmethod void testApexButtonGetDist(){
        
           Account acc = new Account (Name = 'test');
           
           insert acc;
            
           Opportunity opp = new Opportunity(Name = 'Test opp',
           StageName = 'Test Stage',
           CloseDate = date.today());
           insert opp;
           
        ApexPages.StandardController controller = new ApexPages.StandardController(opp);
        ApexButtonGetDist ABGD = new ApexButtonGetDist(controller);
        ABGD.doMyApexLogic();
       
       }           
}

The code Coverage is 53% So How do I increase the code coverage. The code below was not covered.

 theOpportunity.Dist_street__c = getDistributor.BillingStreet;
      theOpportunity.Dist_City__c = getDistributor.BillingCity;
      theOpportunity.Dist_State__c = getDistributor.BillingState;
      theOpportunity.Dist_PostalCode__c = getDistributor.BillingPostalCode;        
      theOpportunity.Distr_SourceCode__c = getDistributor.SourceCode__c;        
        update theOpportunity;
        return new PageReference('/' + theOpportunity.ID);
        
       

Best Answer chosen by Admin (Salesforce Developers) 
Kiran  KurellaKiran Kurella

You need to add Distributor_Name__c in your test opportunity as follows:

 

Opportunity opp = new Opportunity(Name = 'Test opp',
StageName = 'Test Stage',
CloseDate = date.today(),
Distributor_Name__c = acc.Id
);
insert opp;