TransWikia.com

how to mock Object list in a test class?

Salesforce Asked on December 30, 2021

This is a method in my apex controller class:

@AuraEnabled
public static void sendMail(List<Object> selectedRows) {
     if (selectedRows.size() > 0) {
          for (Object obj : selectedRows) {
               Map<Object, Object> mapJson = (Map<Object, Object>)obj;
               String title = (String)mapJson.get('title');
               String link = (String)mapJson.get('link');

               //rest of the code
          }
     }
}

The selectedRows list consist of selected rows from a lightning:datatable which have field names ‘link’ and ‘title’. Here is the code:

<aura:component>
    <lightning:datatable
         keyField="id"
         data="{! v.providerList }"
         columns="{! v.columns }"
         hideCheckboxColumn="false"
         onrowselection="{!c.selectedRowHandler}"/>
</aura:component>

//controller.js
selectedRowHandler: function(component, event, helper) {
    var selectedRows = event.getParam('selectedRows');
    component.set("v.userSelectedRows", selectedRows);
},

userSelectedRows is the attribute I send to the apex method.

This code works fine. The problem I have is that, in the test method of the above method, I cannot mock selectedRows. So, how can I create a Object list with ‘link’ and ‘title’ field names?

One Answer

First, in your actual code, it should be Map<String, Object>, as no other types of keys are valid in JSON. Next, you just need to deserializeUntyped:

List<Object> selectedRows = (List<Object>)JSON.deserializeUntyped(
 '[{"title":"Title1","link":"https://www.google.com"}]');

And pass that in as the parameter.

Answered by sfdcfox on December 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP