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
Pete1234Pete1234 

Calling Apex REST Class from Test Class

Ahhh what fun writing unit tests for the REST API, there seems to be quite a few posts about this and I'm afraid I'm going to add another.

 

I have an Apex REST class that uses a custom class called SAPAccount to hold the details of a JSON message I'm receiving.

 

global static SAPAccount[] doPost( SAPAccount[] sapsoldtos ){
... logic here...
}

 

When I try and call this method in my test class I get the error message "Illegal assignment from LIST<SAPAccountREST.SAPAccount> to SAPAccountREST.SAPAccount".

 

In the test class I'm creating a list of SAPAccounts and then adding to that list.

 

List<SAPAccountREST.SAPAccount> sapAcctList = new List<SAPAccountREST.SAPAccount>();
String jsonMsg = '';

SAPAccountREST.SAPAccount jsonSapAcct = new SAPAccountREST.SAPAccount();
jsonSapAcct.E1KNA1M_KUNNR = '0000000001';
jsonSapAcct.E1KNA1M_NAME = 'Customer Name';
jsonSapAcct.E1KNA1M_STRAS = 'Street';
jsonSapAcct.E1KNA1M_ORT01 = 'Town';
jsonSapAcct.E1KNA1M_PSTLZ = 'Postal Code';
jsonSapAcct.E1KNA1M_LAND1 = 'Country';
jsonSapAcct.E1KNA1M_STCEG = 'Vat';
		
sapAcctList.add( jsonSapAcct );
jsonMsg = JSON.serialize( jsonSapAcct );

 

I then try and call the Apex method using the following code which is when of course the error occurs:

 

SAPAccountREST.SAPAccount results = SAPAccountREST.doPost( sapAcctList );

 

Would greatly appreciate any help that anyone could provide.

Best Answer chosen by Admin (Salesforce Developers) 
MJ Kahn / OpFocusMJ Kahn / OpFocus
The issue isn't REST-related. It's that you defined your doPost method as returning a List, but when you call the method, you're putting the result into a single object. Change either the method definition or where you're putting the result, and you should be fine.

All Answers

MJ Kahn / OpFocusMJ Kahn / OpFocus
The issue isn't REST-related. It's that you defined your doPost method as returning a List, but when you call the method, you're putting the result into a single object. Change either the method definition or where you're putting the result, and you should be fine.
This was selected as the best answer
Pete1234Pete1234

Thanks MJ, after a day of staring at the code I eventually realised that myself!  What is that Homer Simpson normally says?

 

Final code used shown below:

 

List<SAPAccountREST.SAPAccount> results = SAPAccountREST.doPost( sapAcctList );

 

MJ Kahn / OpFocusMJ Kahn / OpFocus

Yeah, I hate it when I do that!

 

Glad you found it! I hope the code is working properly now.

 

MJ.