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
KRITI LAHA 8KRITI LAHA 8 

Can anyone help by writing the test class for this apex class. I am new in coding. need help.

Can anyone help by writing the test class for this apex class. I am new in coding. need help. Thanks

public class HSE_SecurityHealthCheckReport {
    public List<List<String>> getSecurityHealthCheckRisks(){
        List<List<String>> lstValues = new List<List<String>>();
        String baseURL = System.URL.getSalesforceBaseUrl().toExternalForm();
        
        String endpoint = baseURL+'/services/data/v56.0/tooling/query/?q=select+SettingRiskCategory,Setting,OrgValue,StandardValue,RiskType+from+SecurityHealthCheckRisks';
        HttpRequest req = new HttpRequest();
        req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
        req.setHeader('Content-Type', 'application/json');
        req.setEndpoint(endpoint);
        req.setMethod('GET');
        Http h = new Http();
        HttpResponse res = h.send(req);
        String response = res.getBody();
        List<HSE_SHCRWrapper> lstSHCRWpr = new List<HSE_SHCRWrapper>();
        HSE_ResponseWrapper respWpr = new HSE_ResponseWrapper();
        respWpr = (HSE_ResponseWrapper) JSON.deserialize(response, HSE_ResponseWrapper.Class);
        List<String> lstString = new List<String>();
        for(HSE_SHCRWrapper obj: respWpr.records){
            lstString = new List<String>();
            lstString.add(obj.SettingRiskCategory);
            lstString.add(obj.Setting);
            lstString.add(obj.OrgValue);
            lstString.add(obj.StandardValue);
            lstString.add(obj.RiskType);
            lstValues.add(lstString);
        }
        return lstValues;
    }
    
    public static String getSecurityHealthCheck(Blob body){
        List<List<String>> lstValues = new List<List<String>>();
        String baseURL = System.URL.getSalesforceBaseUrl().toExternalForm();
        String endpoint = baseURL+'/services/data/v56.0/tooling/query/?q=SELECT+Id,Score+FROM+SecurityHealthCheck';
        HttpRequest req = new HttpRequest();
        req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
        req.setHeader('Content-Type', 'application/json');
        req.setEndpoint(endpoint);
        req.setMethod('GET');
        Http h = new Http();
        HttpResponse res = h.send(req);
        String response = res.getBody();
        system.debug(response);
        List<HSE_SHCWrapper> lstSHCRWpr = new List<HSE_SHCWrapper>();
        HSE_SHCWRespWrapper respWpr = new HSE_SHCWRespWrapper();
        respWpr = (HSE_SHCWRespWrapper) JSON.deserialize(response, HSE_SHCWRespWrapper.Class);
        HSE_UtilityMethods.CreateCasewithAttchment(body,respWpr.records[0].Score, caseInfoPopulation(respWpr.records[0].Score)[0],caseInfoPopulation(respWpr.records[0].Score)[1]);
        return respWpr.records[0].Score;
    }
    
    public static void sendEmailWithAttachment(){
        PageReference excel = new pagereference('/apex/HSE_healthcheckOutputGenerator');
        Blob body;
        try {
            body = excel.getContent();
           } catch(Exception e){HSECustomException.logException(e);
            body = Blob.valueOf('data');
           }
        String score = getSecurityHealthCheck(body);
        Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
        attach.setContentType('application/vnd.ms-excel');
        attach.setFileName('SecurityRisk.xls');
        attach.Body = body;
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        List<HSE_Security_Distribution_Channel__mdt> reptoaddresses= [Select Email__c from HSE_Security_Distribution_Channel__mdt];
        List<String> toAddresses=new List<String>();
        try{
        for(HSE_Security_Distribution_Channel__mdt securitymail :reptoaddresses )
        {
            toAddresses.add(securitymail.Email__c);
        }
        
        List<emailtemplate> emailtemp=[SELECT Id, DeveloperName, Name, Subject, Body, HtmlValue FROM EmailTemplate where DeveloperName='HSE_Security_Email'];
        String emailBody = emailtemp[0].HtmlValue.replace('{Datetime}',String.valueOf(System.Datetime.now()));
        emailBody = emailBody.replace('{score}',Score);
        mail.setToAddresses(toAddresses);//set from address
        mail.setSenderDisplayName('No Reply');
        mail.setSubject(emailtemp[0].Subject.replace('{Datetime}',String.valueOf(System.Datetime.now())));
        mail.setPlainTextBody('HTML not supported..!');
        mail.setHtmlBody(emailBody);
        mail.setFileAttachments(new Messaging.EmailFileAttachment[] {attach});
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
        }catch(Exception e){HSECustomException.logException(e);}
    }
    
    
    
    public static List<String> caseInfoPopulation(String score){
        Integer scoreInt = Integer.valueOf(score);
        
        List<HSE_HealthcheckThreshold__mdt> healthchkThreshold= [SELECT description__c,higherThreshold__c,lowerThreshold__c 
                                                                 FROM HSE_HealthcheckThreshold__mdt
                                                                 WHERE lowerThreshold__c <=:scoreInt 
                                                                 AND higherThreshold__c >=:scoreInt];
        String subject, description;
        Subject= healthchkThreshold[0].description__c;
        Description= healthchkThreshold[0].description__c;
        return new List<String>{subject,description};
            
        
    }
    
    public class HSE_ResponseWrapper{
        public list<HSE_SHCRWrapper> records = new list<HSE_SHCRWrapper>();
    }
    public class HSE_SHCWRespWrapper{
        public list<HSE_SHCWrapper> records = new list<HSE_SHCWrapper>();
    }
    public class HSE_SHCRWrapper{
        public String SettingRiskCategory;
        public String Setting;
        public String OrgValue;
        public String StandardValue;
        public String RiskType;
    }
    public class HSE_SHCWrapper{
        public String Id;
        public String DurableId;
        public String Score;
    }
}
SwethaSwetha (Salesforce Developers) 
HI Kirti,

The code provided in question does not highlight the uncovered lines in bold. Since this code is huge and requires an understanding of your implementation, it might not be possible to provide exact edit suggestions. You can use below skeletal code to get started
 
@isTest
public class HSE_SecurityHealthCheckReport_Test {
    @isTest
    static void testGetSecurityHealthCheckRisks() {
        // Create test data
        // ...

        // Call the method to be tested
        List<List<String>> result = HSE_SecurityHealthCheckReport.getSecurityHealthCheckRisks();

        // Perform assertions to verify the expected results
        // ...
    }

    @isTest
    static void testGetSecurityHealthCheck() {
        // Create test data
        // ...

        // Call the method to be tested
        Blob body = Blob.valueOf('test body');
        String result = HSE_SecurityHealthCheckReport.getSecurityHealthCheck(body);

        // Perform assertions to verify the expected results
        // ...
    }

    @isTest
    static void testSendEmailWithAttachment() {
        // Create test data
        // ...

        // Call the method to be tested
        Test.startTest();
        HSE_SecurityHealthCheckReport.sendEmailWithAttachment();
        Test.stopTest();

        // Perform assertions to verify the expected results
        // ...
    }

    @isTest
    static void testCaseInfoPopulation() {
        // Create test data
        // ...

        // Call the method to be tested
        String score = '100';
        List<String> result = HSE_SecurityHealthCheckReport.caseInfoPopulation(score);

        // Perform assertions to verify the expected results
        // ...
    }
}

In the test class, you would need to create test data as per your requirements and then call the methods of the HSE_SecurityHealthCheckReport class to test their functionality. You can use assertions to verify that the results are as expected.

See related:
https://salesforce.stackexchange.com/questions/244788/how-do-i-write-an-apex-unit-test
https://salesforce.stackexchange.com/questions/244794/how-do-i-increase-my-code-coverage-or-why-cant-i-cover-these-lines 
 
If this information helps, please mark the answer as best. Thank you