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
RaffusRaffus 

How to write a test method for related objects


@AuraEnabled
    public static List<CaseResultWrapper> getCases(String emailid) {
        try {
            List<CaseResultWrapper> result = new List<CaseResultWrapper>();
            List<String> caseStatuses = new List<String>{'Approved', 'Awaiting Approval', 'Rejected'};
            String query = 'SELECT Id,CaseNumber, Issue_category__c, Points__c, Issue_Sub_Category__c, (SELECT Id, ContentDocumentId FROM ContentDocumentLinks WHERE ContentDocument.FileType != \'wav\'), Status, Country__c, Owner.Name, Description,CreatedDate FROM Case WHERE RecordType.DeveloperName= :rand_APP AND rand_App_Customer__r.Customer_Email__c !=null AND status IN :caseStatuses';
            if (String.isNotBlank(emailid)) {
                query += ' AND rand_App_Customer__r.Customer_Email__c=:emailid';
            }
            /*else if (String.isNotBlank(mobile)) {
                query += 'AND rand_App_Customer__r.Customer_Mobile__c=:mobile';
            }
            else {
                query += 'AND Id = null';
            }*/
            query += ' ORDER BY CreatedDate DESC LIMIT 50'; //CreatedDate = THIS_QUARTER
            System.debug('getCases query   '+query);
            List<Case> cases = Database.query(query);
            Map<Id, Case> contentCaseMap = new Map<Id, Case>();
            for (Case caseRecord : cases) {
                if (caseRecord.ContentDocumentLinks.size() > 0 && caseRecord.ContentDocumentLinks[0].ContentDocumentId != null) {
                    contentCaseMap.put(caseRecord.ContentDocumentLinks[0].ContentDocumentId, caseRecord);
                }
                else {
                    contentCaseMap.put(caseRecord.Id, caseRecord);
                }
            }
            Map<Id, String> contentUrlMap = new Map<Id, String>();
            for (ContentDistribution conDistribution : [SELECT Id, ContentDocumentId, ContentDownloadUrl FROM ContentDistribution WHERE ContentDocumentId IN:contentCaseMap.keySet() ORDER BY CreatedDate ASC]) {
                contentUrlMap.put(conDistribution.ContentDocumentId, conDistribution.ContentDownloadUrl);
            }
            for (Id contentId : contentCaseMap.keySet()) {
                CaseResultWrapper caseWrp = new CaseResultWrapper();
                caseWrp.contentDocId = contentId;
                caseWrp.caseRecord = contentCaseMap.get(contentId);
                caseWrp.imageUrl = contentUrlMap.get(contentId);
                caseWrp.categoryLogoUrl ='';
                DateTime dT = contentCaseMap.get(contentId).CreatedDate;
                If(dT.month()==1){
                    caseWrp.createdDate = dT.day()+'-Jan-'+dT.year();
                    }
                If(dT.month()==2){
                caseWrp.createdDate = dT.day()+'-Feb-'+dT.year();
                }
                If(dT.month()==3){
                caseWrp.createdDate = dT.day()+'-Mar-'+dT.year();
                }
                If(dT.month()==4){
                caseWrp.createdDate = dT.day()+'-Apr-'+dT.year();
                }
                If(dT.month()==5){
                caseWrp.createdDate = dT.day()+'-May-'+dT.year();
                }
                If(dT.month()==6){
                caseWrp.createdDate = dT.day()+'-Jun-'+dT.year();
                }
                If(dT.month()==7){
                caseWrp.createdDate = dT.day()+'-Jul-'+dT.year();
                }
                If(dT.month()==8){
                caseWrp.createdDate = dT.day()+'-Aug-'+dT.year();
                }
                If(dT.month()==9){
                caseWrp.createdDate = dT.day()+'-Sep-'+dT.year();
                }
                If(dT.month()==10){
                caseWrp.createdDate = dT.day()+'-Oct-'+dT.year();
                }
                If(dT.month()==11){
                caseWrp.createdDate = dT.day()+'-Nov-'+dT.year();
                }
                If(dT.month()==12){
                caseWrp.createdDate = dT.day()+'-Dec-'+dT.year();
                }
                result.add(caseWrp);
            }
            return result;
        }
The parameter that i have passed that is email is not in case object but in rand_App_Customer__c object- and case child object of rand_App_Customer__c object- so how i can give the parameter for this method
Below is my test method
 
@IsTest
    public static void getCasesTest(){

        // Id rand_AppRecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('rand_App').getRecordTypeId();
        rand_App_Customer__c randCustomer = new rand_App_Customer__c();
        randCustomer.Customer_ID__c = '1234567';
        randCustomer.Customer_Email__c = 'tannow@tan.ae';
        insert randCustomer;
        
        Case cse = new Case();
        
        cse.Issue_Sub_Category__c = 'Test category';
        cse.Status = 'Approved';   
        cse.Description = 'Test';
        cse.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('rand_App').getRecordTypeId();
        cse.rand_App_Customer__c = randCustomer.Id;

        insert cse;
  
        List<ContentDocument> documents = [SELECT Id,title,LatestPublishedVersionId FROM ContentDocument];
        ContentDocumentLink cdl = new ContentDocumentLink();

        cdl.LinkedEntityId = cse.id;
        cdl.ContentDocumentId = documents[0].Id;
        cdl.shareType = 'V';
        // cdl.FileType = 'jpg';
        insert cdl;

        
        randAppController.getCases('tannow@tan.ae');

}

 
Best Answer chosen by Raffus
Sai PraveenSai Praveen (Salesforce Developers) 
Hi,

I have modified the test class and added logic to create content document and link it with case record.
 
@IsTest
    public static void getCasesTest(){

        // Id rand_AppRecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('rand_App').getRecordTypeId();
        rand_App_Customer__c randCustomer = new rand_App_Customer__c();
        randCustomer.Customer_ID__c = '1234567';
        randCustomer.Customer_Email__c = 'tannow@tan.ae';
        insert randCustomer;
        
        Case cse = new Case();
        
        cse.Issue_Sub_Category__c = 'Test category';
        cse.Status = 'Approved';   
        cse.Description = 'Test';
        cse.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('rand_App').getRecordTypeId();
        cse.rand_App_Customer__c = randCustomer.Id;

        insert cse;
  
        ContentVersion contentVersion = new ContentVersion(
            Title          = 'a picture',
            PathOnClient   = 'Pic.jpg',
            VersionData    = Blob.valueOf('Test Content'),
            IsMajorVersion = true);
    insert contentVersion;

    List<ContentDocument> documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument];

//create ContentDocumentLink  record
    ContentDocumentLink cdl = new ContentDocumentLink();
    cdl.LinkedEntityId = cse.Id;
    cdl.ContentDocumentId = documents[0].Id;
    cdl.ShareType = 'V';
    cdl.Visibility = 'AllUsers';
    insert cdl;

        
        randAppController.getCases('tannow@tan.ae');

}

Let me how much test coverage you got and also share the screenshot which part is not covered after running it.

If this solution helps, Please mark it as best answer.

Thanks,

All Answers

Sai PraveenSai Praveen (Salesforce Developers) 
Hi,

I have modified the test class and added logic to create content document and link it with case record.
 
@IsTest
    public static void getCasesTest(){

        // Id rand_AppRecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('rand_App').getRecordTypeId();
        rand_App_Customer__c randCustomer = new rand_App_Customer__c();
        randCustomer.Customer_ID__c = '1234567';
        randCustomer.Customer_Email__c = 'tannow@tan.ae';
        insert randCustomer;
        
        Case cse = new Case();
        
        cse.Issue_Sub_Category__c = 'Test category';
        cse.Status = 'Approved';   
        cse.Description = 'Test';
        cse.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('rand_App').getRecordTypeId();
        cse.rand_App_Customer__c = randCustomer.Id;

        insert cse;
  
        ContentVersion contentVersion = new ContentVersion(
            Title          = 'a picture',
            PathOnClient   = 'Pic.jpg',
            VersionData    = Blob.valueOf('Test Content'),
            IsMajorVersion = true);
    insert contentVersion;

    List<ContentDocument> documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument];

//create ContentDocumentLink  record
    ContentDocumentLink cdl = new ContentDocumentLink();
    cdl.LinkedEntityId = cse.Id;
    cdl.ContentDocumentId = documents[0].Id;
    cdl.ShareType = 'V';
    cdl.Visibility = 'AllUsers';
    insert cdl;

        
        randAppController.getCases('tannow@tan.ae');

}

Let me how much test coverage you got and also share the screenshot which part is not covered after running it.

If this solution helps, Please mark it as best answer.

Thanks,
This was selected as the best answer
RaffusRaffus
I am getting this error - System.ListException: List index out of bounds: 0 
I think it is because we are passing 'email' in the method, but the email field is missing in the case object, it is present in rand_App_Customer__c
A case is a child object of rand_App_Customer__c- so how can I pass rand_App_Customer__c email as a parameter in the method?
Sai PraveenSai Praveen (Salesforce Developers) 
Hi,

Can you check on which line you are getting this error so can guide you on it.

Thanks,
 
RaffusRaffus
cdl.ContentDocumentId = documents[0].Id;
This line giving error
Sai PraveenSai Praveen (Salesforce Developers) 
Hi,

Did you add the code which is shared for creation of content version. The error is because documents is returning null .

Thanks,
 
RaffusRaffus
Thank you Sai Praveen, it is working now, 
but this part inside if is not covering-
User-added image
 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi,

For this you need to insert diffent content version in different methods setting the created date as january month, feburary month .. etc.

You can set the created date as below.

 
ContentVersion contentVersion = new ContentVersion(
            Title          = 'a picture',
            PathOnClient   = 'Pic.jpg',
            VersionData    = Blob.valueOf('Test Content'),
            IsMajorVersion = true);
    insert contentVersion;

Test.setCreatedDate(contentVersion.Id, DateTime.newInstance(2022,01,01)); 

Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,
RaffusRaffus
Thank you so much
RaffusRaffus
Hi, 
I have tried the above method to cover date using setCreatedDate but it is not working-
@isTest
    public static void getCasesTest2(){

        rand_App_Customer__c randCustomer = [SELECT Id,Customer_ID__c,  Customer_Email__c, Customer_Mobile__c FROM rand_App_Customer__c LIMIT 1];
        randCustomer.Customer_Email__c = 'test@test.com';
        update randCustomer;
		
        System.assertEquals(true,randCustomer != NULL);

        Case caseInfo = [SELECT Id, Issue_Sub_Category__c, rand_App_Customer__c, Status, Description, RecordTypeId FROM Case LIMIT 1];
        caseInfo.rand_App_Customer__c = randCustomer.Id;
        update caseInfo;

       

        System.assertEquals(true,caseInfo != NULL);
        
        ContentVersion contentVersion = new ContentVersion(
            Title          = 'a picture',
            PathOnClient   = 'Pic.jpg',
            VersionData    = Blob.valueOf('Test Content'),
            IsMajorVersion = true);
        insert contentVersion;
        

        List<ContentDocument> documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument];
         System.assertEquals(true,caseInfo != NULL);

        //create ContentDocumentLink  record
        ContentDocumentLink cdl = new ContentDocumentLink();
        cdl.LinkedEntityId = caseInfo.Id;
        cdl.ContentDocumentId = documents[0].Id;
        cdl.ShareType = 'V';
        cdl.Visibility = 'AllUsers';
        insert cdl;

        Test.setCreatedDate(caseInfo.Id, DateTime.newInstance(2022,01,01)); 
        
        randAppController.getCases('test@test.com');
        
    }