+ Start a Discussion
Prince VenkatPrince Venkat 
How to add parameterized method in testclass.
My sample class
public class Training{
public static void work (Account accRec){
----------
-------
}

how to write test class for this

@isTest
private class testClass
{
testmethod static void myTest ()
{
test.starttest();
Training.work ();
test.stoptest();
}
}

getting error

Any Assistance



 
Best Answer chosen by Prince Venkat
CharuDuttCharuDutt
Hii Prince 
Try Below Test Class
@isTest
private class testClass
{
@isTest
public static void myTest ()
{
Account Acc = new Account();
Acc.name='test';
insert Acc;

test.starttest();
Training.work (Acc);
test.stoptest();
}
}
Please Mark It As Best Answer If It Helps
Thank You!

 
ANITHA BEEMUANITHA BEEMU 
This is the apex class:
public class CAMRelatedCases 
{
    private final Account acct;
    public CAMRelatedCases(ApexPages.StandardController setCon) 
    {
        this.acct = (Account)setCon.getRecord();
    }
    public List<Case> getmyCaseList()
    {
        myCaseList = [SELECT ID,CaseNumber, CreatedDate, Subject, AccountID, OwnerID, Account.Name, Owner.Name FROM Case WHERE Account.Dealer_of_Record__c = :this.acct.Id];
        Return myCaseList;
    }
    List<Case> myCaseList = [SELECT ID, CaseNumber, AccountID, OwnerID, CreatedDate, Subject, Description, Account.Name, Owner.Name FROM Case LIMIT 4999];
}


and i wrote test class as follows:

@isTest(seealldata = true)
public class CAMRelatedCasesTest 
{
    Static testMethod void CAMRelatedCases()
    {
        //Creating the account for testing
        account a1 = new account(name = 'test'); 
        Insert a1;
        //Creating the Contact w/email
        contact con = new contact(lastname ='testing', firstname = 'testcontact',email='testingit@gmail.com', accountid = a1.Id);
        
        Case cs = new Case(Account = a1, RecordTypeID = '012500000005eVdAAI', Status = 'Open', Origin = 'Inbound Phone Call', Subject = 'testing for apex class', 
                           Description = 'this needs to be a long description', Update_RMA_Task__c = False);
        Insert cs;
        
        CAMRelatedCases.getmyCaseList();
      }
}


Getting Error:Non static method cannot be referenced from a static context: List<Case> CAMRelatedCases.getmyCaseList()

Please can anyone help..
Best Answer chosen by ANITHA BEEMU
AnkaiahAnkaiah (Salesforce Developers) 
Hi Anitha,
Please use the below modifed test class you will get coverage.

@Istest
Private class CAMRelatedCases_Test {
    
   static testMethod void test1(){
        Account acc = new Account();
        acc.name= 'test';
        acc.Type = 'Prospect';
        insert acc;
        
        case c = new case();
        c.subject = 'test case';
        c.Status = 'New';
        c.AccountId = acc.id;
        insert c;
      ApexPages.StandardController sc = new ApexPages.StandardController(acc);
      CAMRelatedCases testAccPlan = new CAMRelatedCases(sc);
      testAccPlan.getmyCaseList();
   
    }
}

If this helps, Please mark it as best answer

Thank you!!!
ankita sharma 2110ankita sharma 2110 
I am trying to pull values from Googlebooks API for my LWC. Below is my code-->
<template if:true={books}>
                    <template for:each={books.items} for:item="book">
                        <lightning-layout-item size="3" padding="around-small" key={book.id}>
                            <div class="slds-box slds-p-around_medium slds-text-align_center">
                              <img src={book.volumeInfo.imageLinks.smallThumbnail} height="200px">
                              <div class="slds-text-heading_small slds-p-vertical_medium"><strong>{book.volumeInfo.title}</strong></div>
                              <div> <strong>Published Date- {book.volumeInfo.publishedDate}</strong></div>
                              <div> <strong>Average Rating- {book.volumeInfo.averageRating}</strong></div>
                              <!--div><strong>Categories</strong><span>{book.voumeInfo.categories}</span></div-->
                            </div>

JS Code->const BOOK_URL = 'https://www.googleapis.com/books/v1/volumes?q='
export default class BookApp extends LightningElement {
    query='Man'
    books
    connectedCallback(){
        this.fetchBookData()
    }
    fetchBookData(){
        fetch(BOOK_URL+this.query)
    .then(Response=>Response.json())
    .then(data=>{
        console.log(data)
    this.books = data
    })
    .catch(error=>console.error(error))
    }
}


For both the categories and small thumbnail i am getting error -> [Cannot read property 'smallThumbnail' of undefined]
Best Answer chosen by ankita sharma 2110
veer soniveer soni
hy Ankita,
try below code.
import { LightningElement, track } from "lwc";
const BOOK_URL = 'https://www.googleapis.com/books/v1/volumes?q=Man';
export default class FetchDataFromThridPartyInLwc extends LightningElement {
   query='Man'
  books
  connectedCallback(){
      this.fetchBookData()
  }
  fetchBookData(){
      fetch(BOOK_URL+this.query)
  .then(Response=>Response.json())
  .then(data=>{
      console.log('fetch Data from Third Party : ' + JSON.stringify(data));
  let thirdPartyData = data;

let newData = [];
  for(let i=0; i<thirdPartyData.items.length; i++){
    console.log('eachItem : ' + JSON.stringify(thirdPartyData.items[i]));
    let eachItem = thirdPartyData.items[i].volumeInfo;
    if(eachItem.imageLinks == undefined){
        thirdPartyData.items[i].volumeInfo.imageLinks = {"smallThumbnail" : "#####"};
        }
  }
  console.log('thirdPartyData : ' + JSON.stringify(thirdPartyData));
  this.books = thirdPartyData
  })
  .catch(error=>console.log('Third Party Error : ' + JSON.stringify(error)))
  }
}

your error was coming because in actual data imageLinks  this property was not coming in 3-4 item so I did handle them. use above code.
don't forget to mark it as best answer.
Thank you​​​​​​​
Swetha B 7Swetha B 7 
I have an Email to Case set up. Details coming into the body of the email. Need to Parse that Case Description Info into fields in Case. 

Email to the case is set up. The detail comes into the description: 

Contact Form

A user submitted the following information on the Contact us page

Name: XXXX

Phone: XXXX

Email: XXXX

Question/Comments: 

I have fields for each option and I need to pass the information into those fields. the format is the same every time. 

Please correct the trigger logic or provide me the solution for it.

trigger parsingemail on Case (before insert) {
 for(Case C:trigger.new){
        if(C.Subject!=Null && C.Subject.Contains('Contact Form')==True){
        if(C.Description!='' && C.Description.length()>0){
            String data=C.Description;
            C.SuppliedName=data.substringBetween('Name:', 'Phone:'); 
            C.SuppliedPhone=data.substringBetween('Phone:', 'Email:');
            C.SuppliedEmail=data.substringBetween('Email:', 'Question / Comment:');    
            update C;
            }
        }
     }
}

 
Best Answer chosen by Swetha B 7
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Swetha,

In stead of description in the third line of the code change the field to subject as below.
 
trigger CaseTrigger on Case (before insert) {
 for(Case C:trigger.new){
     if(C.subject!=Null && C.subject.Contains('Contact Form')){
        if(C.Description!='' && C.Description.length()>0){   
            String data=C.Description;
            C.SuppliedName=data.substringBetween('Name:', 'Phone:'); 
            C.SuppliedPhone=data.substringBetween('Phone:', 'Email:');
            C.SuppliedEmail=data.substringBetween('Email:', 'Question / Comment:');    
           
            }
        }
     }
}


Thanks

 
Shiri Ronen-Attia 7Shiri Ronen-Attia 7 
When in Lightning and trying to click on 'Generate' Temporary code - that can temorarily be ued instead of MFA if user doesn't have thier mobile device, I get an error "This page has an error" or "You don't have access to this record. Ask your administrator for help or to request access.".

Can someone please enlighten me what access am I missing as the System administrator? 
Something in Identity verification? 
It is working in the Classic UI fine, the error is just in the Lightning UI.
Any advise is welcome!
Best Answer chosen by Shiri Ronen-Attia 7
SwethaSwetha (Salesforce Developers) 
HI Shiri,
The issue you are facing is related to the known issue-  https://trailblazer.salesforce.com/issues_view?title=generate-temporary-verification-code-issue-in-lightning&Id=a1p3A000000AU7w

Salesforce Investigation #W-4992937

While there is no ETA for a fix at the moment, please consider selecting "This Issue Affects me" so that the fix can be prioritized.

If this information helps, please mark the answer as best.

Thank you
Swetha Maddali
Salesforce support
Megan RuncimanMegan Runciman 
Hi,

I am trying to use the guides to integrate Salesforce & Mailchimp, however some of the work has already been started and I cannot go back.

I am receiving the following error when at the Mappings stage;

"Modify" permission to field "MC4SF__Prompt_For_Full_Sync__c" on object "MC4SF__MC_List__c" is not allowed for the current user.
Error is in expression '{!saveStep3}' in page mc4sf:install: (MC4SF)
An unexpected error has occurred. Your solution provider has been notified. (MC4SF)

Please help!
Best Answer chosen by Megan Runciman
ShivankurShivankur (Salesforce Developers) 
Hi Megan,

Looking at the error, it looks like there is permission issue with the field from an object came via managed package.  You can manage to report this with managed package provider and they could be able to able to provide a resolution. 

Since, managed package provider would have full access to the code and functionality, they should be able to provide some suggestion on this.

You could also get in touch with them via below link:
https://us1.admin.mailchimp.com/support/

Hope above information helps. Please mark as Best Answer so that it can help others in future.

Thanks.
Vijay ummedaVijay ummeda 
Hi Team,

I am trying to create a validation Rule i have custom Field called status it has 4 picklist values(NEW,old,current,upgraded) when any one of the value is selected user shou;ld not be able to edit the Fields.


AND(
    ISPICKVAL( status__c,'NEW'),
    OR(
        ISCHANGED( NHPMS__Re_Admit__c ),
        ISCHANGED( NHPMS__Discharge_Date__c ),
        ISCHANGED( Next_Appointment__c )
)
    ISPICKVAL( status__c,'old'),
    OR(
        ISCHANGED( NHPMS__Re_Admit__c ),
        ISCHANGED( NHPMS__Discharge_Date__c ),
        ISCHANGED( Next_Appointment__c ))
    )
    ISPICKVAL( status__c,'current'),
    OR(
        ISCHANGED( NHPMS__Re_Admit__c ),
        ISCHANGED( NHPMS__Discharge_Date__c ),
        ISCHANGED( Next_Appointment__c ))
    
)
    ISPICKVAL( status__c,'upgraded'),
    OR(
        ISCHANGED( NHPMS__Re_Admit__c ),
        ISCHANGED( NHPMS__Discharge_Date__c ),
        ISCHANGED( Next_Appointment__c ))
    
)
)
Best Answer chosen by Vijay ummeda
Surya GSurya G
Hi Vijay,
try this if this works.

AND(
        OR(
             ISCHANGED( NHPMS__Re_Admit__c ),
             ISCHANGED( NHPMS__Discharge_Date__c ),
             ISCHANGED( Next_Appointment__c )
             ),
        OR(
              ISPICKVAL( status__c,'NEW'),
              ISPICKVAL( status__c,'old'),
              ISPICKVAL( status__c,'current'),
              ISPICKVAL( status__c,'upgraded')
           )
        )
Thanks 
Surya G
Rohan TelangRohan Telang 
Hello,
We have created a form in our website to submit info that will create a Order in Salesforce.  Three of the Fields we have in Order object are 
"EffectiveDate","License_activation_date__c" and "License_Expiration_date__c". I am submitting the date in the correct format of yyyy-MM-dd and the API request is correct and the response back is successful. However, when I am submmiting the request in the body, it's giving error.
I am submitting the JSON in the body as follows-

[
{
    "accountId":"0015E00001eJboYQAS",
    "licenseActivationDate":"2020-08-03",
    "licenseExpirationDate":"2021-10-11",
    "orderStartDate":"2021-08-21",
    "status":"Draft",
    "contractNumber":"8005E000002VXzxQAG"
}
]


But, it's giving error as Expected EGS_Order_API.DateValue but found "2020-08-03" at [line:3, column:37]

My REST API Class is as follows-

@RestResource(urlMapping='/OrderForWebTeam/*')
global class EGS_OrderForWebTeam {
    
    public class OrderData{
        public Id accountId;
        public String orderName;
        public String customerId;
        public Decimal currencys;
        public String billingStreet;
        public String billingCity;
        public String billingState;
        public String billingPostalCode;
        public String billingCountry;
        public String status;
        public String orderAmount;
        public DateValue orderStartDate;
        public String orderType;
        public DateValue licenseActivationDate;
        public DateValue licenseExpirationDate;
        public Id productId;
        public String entitlementId;    
        public Id contractNumber;    
    }
    
    public class DateValue{
        public Integer day;
        public Integer month;
        public Integer year;
    }
    
    @httpPost
    global static void createOrderData(){
        try{
            RestRequest req = RestContext.request;
            String jsonString = req.requestBody.tostring();
            List<OrderData> receivedData = (List<OrderData>)System.JSON.deserialize(jsonString, List<OrderData>.class);
            
            List<Order> orderList = new List<Order>();
            for(OrderData oData:receivedData){
                Order orderObject= New Order();
                orderObject.AccountId=oData.accountId;
                orderObject.Name=oData.orderName;
                orderObject.Customer_ID__c=oData.customerId;
                orderObject.Currency__c=oData.currencys;
                orderObject.BillingStreet=oData.billingStreet;
                orderObject.BillingCity=oData.billingCity;
                orderObject.BillingState=oData.billingState;
                orderObject.BillingPostalCode=oData.billingPostalCode;
                orderObject.BillingCountry=oData.billingCountry;
                orderObject.Status=oData.status;
                orderObject.Type=oData.orderType;
                orderObject.License_activation_date__c= Date.newInstance(oData.licenseActivationDate.year,oData.licenseActivationDate.month,oData.licenseActivationDate.day);
                orderObject.License_Expiration_date__c= Date.newInstance(oData.licenseExpirationDate.year,oData.licenseExpirationDate.month,oData.licenseExpirationDate.day);
                orderObject.EffectiveDate= Date.newInstance(oData.orderStartDate.year,oData.orderStartDate.month,oData.orderStartDate.day);
                orderObject.Product_name__c=oData.productId;
                orderObject.Entitlement_ID__c=oData.entitlementId;
                orderObject.ContractId=oData.contractNumber;
                
                orderList.add(orderObject);
            }
            insert orderList;
            RestResponse res = RestContext.response;
            res.statusCode = 200;
            res.responseBody = Blob.valueOf('Order Inserted Successfully..');
        }catch(Exception e){
            RestResponse res = RestContext.response;
            res.statusCode = 404;
            res.responseBody = Blob.valueOf('Something went wrong! Error Message : '+e.getMessage());
        }
    }
    
}



Does anyone have any idea what could be the problem?

Thanks !!
Best Answer chosen by Rohan Telang
Maharajan CMaharajan C
Hi Roham,

I don't know why you have created the seperate wrapper class for Date. It's not needed and you can directly use the date value from JSON because your date format in JSON looks fine.

Please try the below changes in your apex class:
 
@RestResource(urlMapping='/OrderForWebTeam/*')
global class EGS_OrderForWebTeam {
    
    public class OrderData{
        public Id accountId;
        public String orderName;
        public String customerId;
        public Decimal currencys;
        public String billingStreet;
        public String billingCity;
        public String billingState;
        public String billingPostalCode;
        public String billingCountry;
        public String status;
        public String orderAmount;
        public Date orderStartDate;
        public String orderType;
        public Date licenseActivationDate;
        public Date licenseExpirationDate;
        public Id productId;
        public String entitlementId;    
        public Id contractNumber;    
    }
    
    @httpPost
    global static void createOrderData(){
        try{
            RestRequest req = RestContext.request;
            String jsonString = req.requestBody.tostring();
            List<OrderData> receivedData = (List<OrderData>)System.JSON.deserialize(jsonString, List<OrderData>.class);
            
            List<Order> orderList = new List<Order>();
            for(OrderData oData:receivedData){
                Order orderObject= New Order();
                orderObject.AccountId=oData.accountId;
                orderObject.Name=oData.orderName;
                orderObject.Customer_ID__c=oData.customerId;
                orderObject.Currency__c=oData.currencys;
                orderObject.BillingStreet=oData.billingStreet;
                orderObject.BillingCity=oData.billingCity;
                orderObject.BillingState=oData.billingState;
                orderObject.BillingPostalCode=oData.billingPostalCode;
                orderObject.BillingCountry=oData.billingCountry;
                orderObject.Status=oData.status;
                orderObject.Type=oData.orderType;
                orderObject.License_activation_date__c= oData.licenseActivationDate;
                orderObject.License_Expiration_date__c= oData.licenseExpirationDate;
                orderObject.EffectiveDate= oData.orderStartDate;
                orderObject.Product_name__c=oData.productId;
                orderObject.Entitlement_ID__c=oData.entitlementId;
                orderObject.ContractId=oData.contractNumber;
                
                orderList.add(orderObject);
            }
            insert orderList;
            RestResponse res = RestContext.response;
            res.statusCode = 200;
            res.responseBody = Blob.valueOf('Order Inserted Successfully..');
        }catch(Exception e){
            RestResponse res = RestContext.response;
            res.statusCode = 404;
            res.responseBody = Blob.valueOf('Something went wrong! Error Message : '+e.getMessage());
        }
    }
    
}

Thanks,
Maharajan.C
fiona gentryfiona gentry 
Dear gurus,

I have a problem where 

GIVEN there is a string of characters, and i need to ivoke a reverse method is invoked such that it returns an array of characters in reversed order for alphanumeric characters only however all other non-alphanumeric characters need to retain their original position -
How to Implement solution in Apex?

I tried below code but no luck
public class assessment {
  public static List<String> reverseSpecialString(String input) {
        List<String> resultList = new List<String>();
         // IMPLEMENT
        resultList = input.split('');
        string reversedString='';
        for(integer i=resultList.size()-1;i>=0;i--)
            {
             
            reversedString=reversedString+resultList[i];
               
            }
    
       
        
        
         return resultList;
      
       }
    
    public static void validateSolution() {
        String input = 'ABC@HI#J2';
        List<String> expected = new List<String> {'2','J','I','@','H','C','#','B','A'};
        List<String> actual = reverseSpecialString(input);
        
        System.assertEquals(expected, actual, 'Invalid Results');
    }
}

Thanks,
Fiona​​​​​​​

 
Best Answer chosen by fiona gentry
Surya GSurya G
Hi Fiona,
we can use isAlphaNumeric() method to check the string characters and reverse it , and add the nonalphanumeric values at the exact index position using map.
public class assessment {
  public static List<String> reverseSpecialString(String input) {
    List<String> inputList = input.split('');
    Map<Integer,String> stringMap = new Map<Integer,String>();
    List<String> output = new List<String>();
    for (Integer i=0; i<inputList.size(); i++) {
        String charac = inputList[i];
        if(!charac.isAlphaNumeric()) {
            stringMap.put(i,charac);
        }else {
            output.add(charac);
        }
    }
    String finalString =  String.join(output,'');
    List<String> resultList = finalString.reverse().split('');
    for( Integer I : stringMap.keySet() ){
        system.debug(I);
        resultList.add(I,stringMap.get(I));
	}
      return resultList;
  }  
}
Let me know if that helps.

Thanks
Surya G

 
Sayantika DuttaSayantika Dutta 
public class CreateContactcls {
	@Auraenabled
    public static string createContact(Contact contObj){
    	//System.debug('contact::'+contObj.LastName);
        upsert contObj;
        return contObj.Id;
    }
}


<aura:component implements="flexipage:availableForAllPageTypes" access="global" controller="CreateContactcls">
	<aura:attribute name="contactObj" type="Contact" default="{'sobjectType':'Contact',
                                                              'FirstName':'',
                                                              'LastName':'',
                                                              'Phone':''}"/>
    <aura:attribute name="contactId" type="String"/>
    
    <article class="slds-card">
        <div class="slds-card__header slds-grid">
    <header class="slds-media slds-media_center slds-has-flexi-truncate">
        <div class="slds-media__figure">
            <span class="slds-icon_container slds-icon-standard-account" title="account">
                <lightning:icon iconName="standard:contact" alternativeText="Contact"/>
            </span>
        </div>
        <div class="slds-media__body">
            <h2 class="slds-card__header-title">
                <a href="javascript:void(0);" class="slds-card__header-link slds-truncate" title="Accounts">
                    <span>Contact</span>
                </a>
            </h2>
        </div>
        
            </header>
        </div>
        <div class="slds-card__body slds-card__body_inner">
            <div class="slds-size_1-of-3">
    	<lightning:input value="{!v.contactObj.FirstName}" label="First Name" required="true" placeholder="Enter first name..."/>
                   
        <lightning:button variant="neutral" label="Reset" type="Submit" iconName="utility:close" iconPosition="left" onclick="{!c.hide}" />
        <lightning:input value="{!v.contactObj.LastName}" label="Last Name" required="true" placeholder="Enter last name..."/>
    	<lightning:input value="{!v.contactObj.Phone}" label="Phone" required="true" placeholder="Enter phone no..." name="tel"  pattern="^[0-9_ ]*$" maxlength="11"
                     messageWhenPatternMismatch="Phone number is not valid"
                    
                    />
                <div class="slds-no-flex">
        <center><lightning:button variant="brand" label="Save" title="Save" onclick="{!c.doSave}"/></center>
                    
            
        </div>
        </div>
        </div>
    
            
            </article>
            
                     
</aura:component>


({
	doSave : function(component, event, helper) {
		var action = component.get("c.createContact");
        action.setParams({'contObj':component.get('v.contactObj')});
        action.setCallback(this,function(data){
            component.set('v.contactId',data.getReturnValue())
        });
        $A.enqueueAction(action);
       var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            "title": "Success!",
            "message": "The record has been Created successfully."
        });
        toastEvent.fire();
        
    },
    checkValidity : function(component, event, helper) {
        var validity = event.getSource().get("v.validity");
        console.log(validity)
    },
      hide : function(component,event,helper){
        component.set('v.contactObj.FirstName','');
    },
    
    
    
})
When I'm clicking the save button, 

This page has an error. You might just need to refresh it. Action failed: c:ContactRecCreation$controller$doSave [Cannot read property 'setParams' of undefined] Failing descriptor: {c:ContactRecCreation$controller$doSave}

This error is coming. Can anyone please help me solving the issue?

 
Best Answer chosen by Sayantika Dutta
Maharajan CMaharajan C
Hi Sayantika,

Don't put the toastEvent after the enqueueAction.

Please use the below doSave JS method :
 
doSave : function(component, event, helper) {
        var action = component.get("c.createContact");
        //action.setParams({contObj : component.get('v.contactObj')});
        action.setParams({ contObj : component.get("v.contactObj")});
        action.setCallback(this,function(data){
            console.log(' response==> ' + data.getReturnValue());
            component.set('v.contactId',data.getReturnValue());
            var toastEvent = $A.get("e.force:showToast");
            toastEvent.setParams({
                "title": "Success!",
                "message": "The record has been Created successfully."
            });
            toastEvent.fire();
            
        });
        $A.enqueueAction(action);
    },


Thanks,
Maharajan.C