+ Start a Discussion
Kishan Kumar 77Kishan Kumar 77 

This my custom controller which is used for searching opportunity and sending the data using Http REST Callout. I need to write test class for both the methods. Can someone please help me. Thanks in advance.

public with sharing class OppSearch {
    
    public List<Opportunity> OppList { get; set; }
    
    public String searchText { get; set; }
    public static Id selectedRec {get;set;}
    public integer totalRecs = 0;
    public integer OffsetSize = 0;
    public integer LimitSize= 5;
    public OppSearch()
    {
        
        OppList = new List<Opportunity>();
        
    }
    
    public PageReference searchOpportunity()
        
    {
        OppList = new List<Opportunity>();
        
        if(String.isBlank(searchText))
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter some value'));
        }
        
        
        
        if(String.isNotBlank(searchText))
        {
            if(searchText.isNumeric())
            {
                Decimal searchstringDouble = decimal.valueOf(searchText);
                
                OppList = [select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                           
                           from Opportunity
                           
                           where Amount=:searchstringDouble LIMIT :LimitSize OFFSET :OffsetSize];
                totalRecs = OppList.size();
                
                if(OppList.size()==0)
                {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Search failed as criteria do not match'));
                }
                
            }
            else {
                String newSearchText = searchText+'%';
                
                OppList =[select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                          
                          from Opportunity
                          where Name like:newSearchText or Account.Name like:newSearchText
                          or StageName like:newSearchText or Type like:newSearchText LIMIT :LimitSize OFFSET :OffsetSize];
                totalRecs = OppList.size();
                
                if(OppList.size()==0)
                {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Search failed as criteria do not match'));
                }
                
            }
            
        }
        return null;
    }
    public pageReference FirstPage()
    {
        OffsetSize = 0;
        searchOpportunity();
        return null;
    }
    public pageReference previous()
    {
        OffsetSize = OffsetSize - LimitSize;
        searchOpportunity();
        return null;
    }
    public pageReference next()
    {
        OffsetSize = OffsetSize + LimitSize;
        
        searchOpportunity();
        return null;
    }
    public pageReference LastPage()
    {
        OffsetSize = totalrecs - math.mod(totalRecs,LimitSize);
        
        searchOpportunity();
        return null;
    }
    public boolean getprev()
    {
        if(OffsetSize == 0)
            return true;
        else
            return false;
    }
    public boolean getnxt()
    {
        if((OffsetSize + LimitSize) > totalRecs)
            
            return true;
        else
            return false;
    } 
    public static HttpResponse sendData()
    {
        Opportunity op=[select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                        
                        from Opportunity
                        
                        where Id = :selectedRec];
        
        JSONGenerator gen = JSON.createGenerator(true);   
        gen.writeStartObject();     
        gen.writeStringField('Name ', op.Name);
        
        gen.writeStringField('Account',op.Account.Name);
        gen.writeStringField('Stage',op.StageName);
        gen.writeStringField('Type',op.Type);
        gen.writeNumberField('Amount',op.Amount);
        gen.writeDateField('Close Date',op.CloseDate);
        gen.writeEndObject();   
        String jsonS = gen.getAsString();
        System.debug('jsonMaterials'+jsonS);
        
        // Sending the http body with JSON
        
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        // Set the body as a JSON object
        request.setBody(jsonS);
        HttpResponse response = http.send(request);
        if (response.getStatusCode() != 201)
        {
            Opportunity o= [select Integration_Comments__c,Integration_Status__c from Opportunity
                            where Id =:selectedRec];  
            o.Integration_Status__c='Not Successful';
            o.Integration_Comments__c=response.getStatus();
            update o;
            System.debug(response.getStatusCode());
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Opps! your Callout was not successful'));
        }
        
        else {
            
            Opportunity o= [select Integration_Comments__c,Integration_Status__c from Opportunity
                            where Id =:selectedRec]; 
            
            o.Integration_Status__c='Success';
            o.Integration_Comments__c='Success';
            update o;
            System.debug(response.getStatusCode());
        }
      return response;
    }
    
}
 
Best Answer chosen by Kishan Kumar 77
Maharajan CMaharajan C
Hi Kishan,

1.  First  to Cover the HTTP callouts you must have to create new HTTP Mock Callout Class :

Copy the below code and create the new class in your org:
@isTest
global class OppsendDataMock implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest request) {
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"Name " : "Test Opp","Account" : "Test Account","Stage" : "Prospecting","Type" : "New Customer","Amount" : 10000.00, "Close Date" : "2020-08-10"}');
        response.setStatusCode(200);
        return response; 
    }
}

2. Once the above class created use the below update test class for controller:
 
@isTest
public class OppSearchTest {
    Static testmethod void testOppSearchbyAmount(){
        
        Account acc = new Account(Name = 'Test Account');
        insert acc;
        
        List<Opportunity> oppList = new List<Opportunity>();
        for(integer i = 0; i < 10 ; i++)
        {
            Opportunity opp = new Opportunity(Name ='Test Opp'+i,StageName='Prospecting',Amount=10000,CloseDate = system.today() + 60,AccountId = acc.Id);
            oppList.add(opp);
        }
        insert oppList;
        
        OppSearch os = new OppSearch();
        os.searchText = String.valueOf('10000');
        
        Test.startTest();
        os.searchOpportunity();
        os.FirstPage();
        os.LastPage();
        os.previous();
        os.next();
        os.getprev();
        os.getnxt();
        Test.stopTest();
    }
    
    Static testmethod void testOppSearchbyName(){
        
        Account acc = new Account(Name = 'Test Account');
        insert acc;
        
        List<Opportunity> oppList = new List<Opportunity>();
        for(integer i = 0; i < 10 ; i++)
        {
            Opportunity opp = new Opportunity(Name ='Test Opp'+i,StageName='Prospecting',Amount=10000,CloseDate = system.today() + 60,AccountId = acc.Id);
            oppList.add(opp);
        }
        insert oppList;
        
        OppSearch os = new OppSearch();
        os.searchText = acc.Name;
        
        Test.startTest();
        os.searchOpportunity();
        os.FirstPage();
        os.LastPage();
        os.previous();
        os.next();
        os.getprev();
        os.getnxt();
        Test.stopTest();
    }
    
    Static testmethod void testOppSearchsendData(){
        
        Account acc = new Account(Name = 'Test Account');
        insert acc;
        
        Opportunity opp = new Opportunity(Name ='Test Opp',AccountId=acc.Id,StageName='Prospecting',Amount=10000,CloseDate = system.today() + 60,Type = 'New Customer');
        insert opp;
        
        OppSearch.selectedRec = opp.Id;
        
        Test.setMock(HttpCalloutMock.class, new OppsendDataMock());  
        
        Test.startTest();
        OppSearch.sendData();
        Test.stopTest();
    }
    
    
    Static testmethod void testOppSearchNegative(){
        
        OppSearch os = new OppSearch();
        os.searchText = '';
        os.searchOpportunity();
        
        OppSearch os1 = new OppSearch();
        os1.searchText = 'Opp Search';
        os1.searchOpportunity();
        
        OppSearch os2 = new OppSearch();
        os2.searchText = '5000';
        os2.searchOpportunity();
    }
}

I know you will get good coverage based on above code but try to include assert statements in each method to verify the test logic are working as expected. 

Thanks,
Maharajan.C

All Answers

Maharajan CMaharajan C
Hi Kishan,

1.  First  to Cover the HTTP callouts you must have to create new HTTP Mock Callout Class :

Copy the below code and create the new class in your org:
@isTest
global class OppsendDataMock implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest request) {
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"Name " : "Test Opp","Account" : "Test Account","Stage" : "Prospecting","Type" : "New Customer","Amount" : 10000.00, "Close Date" : "2020-08-10"}');
        response.setStatusCode(200);
        return response; 
    }
}

2. Once the above class created use the below update test class for controller:
 
@isTest
public class OppSearchTest {
    Static testmethod void testOppSearchbyAmount(){
        
        Account acc = new Account(Name = 'Test Account');
        insert acc;
        
        List<Opportunity> oppList = new List<Opportunity>();
        for(integer i = 0; i < 10 ; i++)
        {
            Opportunity opp = new Opportunity(Name ='Test Opp'+i,StageName='Prospecting',Amount=10000,CloseDate = system.today() + 60,AccountId = acc.Id);
            oppList.add(opp);
        }
        insert oppList;
        
        OppSearch os = new OppSearch();
        os.searchText = String.valueOf('10000');
        
        Test.startTest();
        os.searchOpportunity();
        os.FirstPage();
        os.LastPage();
        os.previous();
        os.next();
        os.getprev();
        os.getnxt();
        Test.stopTest();
    }
    
    Static testmethod void testOppSearchbyName(){
        
        Account acc = new Account(Name = 'Test Account');
        insert acc;
        
        List<Opportunity> oppList = new List<Opportunity>();
        for(integer i = 0; i < 10 ; i++)
        {
            Opportunity opp = new Opportunity(Name ='Test Opp'+i,StageName='Prospecting',Amount=10000,CloseDate = system.today() + 60,AccountId = acc.Id);
            oppList.add(opp);
        }
        insert oppList;
        
        OppSearch os = new OppSearch();
        os.searchText = acc.Name;
        
        Test.startTest();
        os.searchOpportunity();
        os.FirstPage();
        os.LastPage();
        os.previous();
        os.next();
        os.getprev();
        os.getnxt();
        Test.stopTest();
    }
    
    Static testmethod void testOppSearchsendData(){
        
        Account acc = new Account(Name = 'Test Account');
        insert acc;
        
        Opportunity opp = new Opportunity(Name ='Test Opp',AccountId=acc.Id,StageName='Prospecting',Amount=10000,CloseDate = system.today() + 60,Type = 'New Customer');
        insert opp;
        
        OppSearch.selectedRec = opp.Id;
        
        Test.setMock(HttpCalloutMock.class, new OppsendDataMock());  
        
        Test.startTest();
        OppSearch.sendData();
        Test.stopTest();
    }
    
    
    Static testmethod void testOppSearchNegative(){
        
        OppSearch os = new OppSearch();
        os.searchText = '';
        os.searchOpportunity();
        
        OppSearch os1 = new OppSearch();
        os1.searchText = 'Opp Search';
        os1.searchOpportunity();
        
        OppSearch os2 = new OppSearch();
        os2.searchText = '5000';
        os2.searchOpportunity();
    }
}

I know you will get good coverage based on above code but try to include assert statements in each method to verify the test logic are working as expected. 

Thanks,
Maharajan.C
This was selected as the best answer
Kishan Kumar 77Kishan Kumar 77
Thank You so much Maharajan!!! It was really helpful
Kishan Kumar 77Kishan Kumar 77
Maharajan i made few changes to my controller and now it gives 90% code coverage and before making the changes it was 97%. Can you please help me with that