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


how to write test case for this code?


public Account retrieveOrganisation(String orgId) {
      Account retOrg = new Account();
        String strQuery = 'SELECT ';
        Map<String, Schema.sObjectField> mpFields = Schema.sObjectType.Account.fields.getMap();
        Set<String> geoFieldPrefixes = new Set<String>();
        for (Schema.sObjectField fld: mpFields.values()) if (fld.getDescribe().getName().contains('Longitude') || fld.getDescribe().getName().contains('Latitude')) geoFieldPrefixes.add(fld.getDescribe().getName().split('__',2)[0]);
        for (Schema.sObjectField fld: mpFields.values()) {
            String fldName=fld.getDescribe().getName();
            if (!geoFieldPrefixes.contains(fldName.split('__',2)[0])) strQuery+=fldName+',';
        if (strQuery.endsWith(',')) strQuery = strQuery.substring(0, strQuery.length() - 1);
        strQuery+=' FROM Account WHERE Id=\''+orgId+'\' LIMIT 1';
        System.debug('### OUTPUT >>>>> retrieveOrganisation: strQuery: '+strQuery);
        retOrg = Database.query(strQuery);
        return retOrg;

Hi venkat,


You have to make some changes to your controller then after write test class. below is the changed code whose code coverage is 93%.


Apex class:

public Account retrieveOrganisation(String orgId) {        
        Account retOrg = new Account();
        String strQuery = 'SELECT ';
        Map<String, Schema.sObjectField> mpFields = Schema.sObjectType.Account.fields.getMap();
        Set<String> geoFieldPrefixes = new Set<String>();
        for (Schema.sObjectField fld: mpFields.values()) if (fld.getDescribe().getName().contains('Longitude') || fld.getDescribe().getName().contains('Latitude')) geoFieldPrefixes.add(fld.getDescribe().getName().split('__',2)[0]);
        for (Schema.sObjectField fld: mpFields.values()) {
            String fldName=fld.getDescribe().getName();
            if (!geoFieldPrefixes.contains(fldName.split('__',2)[0])) strQuery+=fldName+',';
        if (strQuery.endsWith(',')) strQuery = strQuery.substring(0, strQuery.length() - 1);
        strQuery+=' FROM Account WHERE Id=\''+orgId+'\' LIMIT 1';
        System.debug('### OUTPUT >>>>> retrieveOrganisation: strQuery: '+strQuery);
        List<Account> lstAccount = Database.query(strQuery);
        if(lstAccount.size() > 0){
            retOrg = lstAccount[0];
        return retOrg;

 Test class:

public class Testctrlmadetestclass{
    Private Static testmethod void Testctrlmadetestclass(){
        YourclassName objYourclassName = new YourclassName();




Important :
Hit Kudos if this provides you with useful information and if this is what you where looking for then please mark it as a solution for other benefits.

Hitesh Patel
SFDC Certified Developer & Administrator