I came across a question in a developer community on how to write Unit Test Classes for the Rest API service for POST HTTP calls
Unit Test Classes for REST API following link is very useful and inspired by this jeff had an article on his blog on how to write the test method for same .
Here is the Jeff Blog Link Test Class for REST API(Good reference for GET Rest Services)
In one of my previous blog post i demonstrated how to use native parsing technique for Rest api for User Defined Type Unit Test Classes for REST API following link is very useful and inspired by this jeff had an article on his blog on how to write the test method for same .
Here is the Jeff Blog Link Test Class for REST API(Good reference for GET Rest Services)
I wrote the Test class for the same and this post is helpful for all those searching for how to write test classes for apex rest service annotated with POST Call
Here is the Rest Service Class for which i attempted the test class
@RestResource(urlMapping='/DemoUrl/*') global with sharing class MyRestResourcedemo { global class RequestWrapper{ public Account acct; public Contact[] cons; } global class ResponseWrapper { public String StatusCode; public String StatusMessage; public Account acct; public Contact[] cons; } @HttpPost global static ResponseWrapper doPost(RequestWrapper reqst) { ResponseWrapper resp = new ResponseWrapper(); try{ insert reqst.acct; for(Contact c:reqst.cons){ c.AccountId = reqst.acct.Id; } Upsert reqst.cons; } catch( Exception e ) { resp.statusCode = 'Error'; resp.statusMessage = 'Exception : ' + e.getMessage(); } resp.statusCode = 'Done'; resp.statusMessage = 'Test success message'; resp.acct = reqst.acct; resp.cons = reqst.cons; return resp; } }Here is how i wrote my Test class and it ensured my class is covered and i aserted the response
@istest public class SFA_TestRestPostService { static testMethod void testPostRestService(){ Account acc=new Account(); acc.name='Test'; acc.AccountNumber='1232332'; acc.Site='site'; acc.Website='cloudyworlds.blogspot.in'; Listlstcon=new List (); integer i; for(i=0;i<=10;i++){ Contact c=new Contact(); c.lastname='Test+i'; lstcon.add(c); } MyRestResourcedemo.RequestWrapper reqst=new MyRestResourcedemo.RequestWrapper(); reqst.acct=acc; reqst.cons=lstcon; String JsonMsg=JSON.serialize(reqst); Test.startTest(); //As Per Best Practice it is important to instantiate the Rest Context RestRequest req = new RestRequest(); RestResponse res = new RestResponse(); req.requestURI = '/services/apexrest/DemoUrl'; //Request URL req.httpMethod = 'POST';//HTTP Request Type req.requestBody = Blob.valueof(JsonMsg); RestContext.request = req; RestContext.response= res; MyRestResourcedemo.ResponseWrapper resp =new MyRestResourcedemo.ResponseWrapper(); resp=MyRestResourcedemo.doPost(reqst); //Call the Method of the Class with Proper Constructor System.assert(resp.statusMessage.contains('Test success message'));//Assert the response has message as expected System.assert(resp.statusCode.contains('Done')); System.assert(resp.acct.Id!=null);//Assert that the Account is inserted and has Id Test.stopTest(); } }
Some thoughts on best practice can be found on this link of stackexchange
http://salesforce.stackexchange.com/questions/4988/writing-test-classes-for-apex-restservice
Can you provide an example of how the JSON string would be constructed, in particular when creating multiple contacts. I'm using cURL to post data using your sample code and can't figure it out?
ReplyDeletehttps://workbench.developerforce.com/ cURL will be tedious to use .Try using salesforce workbench .The REST utility embedded in workbench is good tool to test.
DeleteTry using the JSON.Serialise method to generate the JSON.
List lstcnts=[Select Id,Name from contact limit 10];
String body=JSON.Serialise(lstcnts);
This should help you
thank you for giving this information
DeleteHome work writing help in uk
Hi Im itching to know if I may use this article in one of my blogs if I link back to you? Thanksurl
ReplyDeleteThank you because you have been willing to share information with us. we will always appreciate all you have done here because I know you are very concerned with our. essay writing
ReplyDeleteThank you for taking the time to publish this information very useful! essay writing service
ReplyDeleteThe data you have posted is extremely valuable. The locales you have alluded was great. A debt of gratitude is in order for sharing... cheap essay writer
ReplyDeleteNice post mate, keep up the great work, just shared this with my friendz cuevana peliculas on line
ReplyDeleteIt is acceptable that you generally notice the positive picture of these kinds of themes yet then again on the off chance that you need related help. I truly love this post and would like to see such educational news besides. Keep it up. pro writing aid
ReplyDeleteseo company malaysia
ReplyDeleteThe data you have posted is extremely valuable. The locales you have alluded was great. A debt of gratitude is in order for sharing
ReplyDeletepromise day wishes
hug day quotes
Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. link
ReplyDeletePerfectly define! I love the way you write! We are also an assignment writing provider in Australia, US and UK.
ReplyDeleteRead more: Differential Equations Assignment Help
All the contents you mentioned in post is too good and can be very useful. I will keep it in mind, thanks for sharing the information keep updating, looking forward for more posts.Thanks buy essay cheap
ReplyDeleteThere are many advantages to having professional editing services correct the proofs of your research or school essay. There are usually Teachers or professors who will review these types of tests and look for a certain tone type of argument. Having a professional writer who has experience with school tests can help you turn mediocre writing to superb writing. reddit essay writing service
ReplyDeleteI just want to let you know that I just check out your site and I find it very interesting and informative.. Atlanta Limousine
ReplyDeleteI would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. Thanks... credit repair Michigan
ReplyDeleteGot the weekend homework blues? Do not fret. Leave the homework to us. Be it research papers, discussions, questions and bibliographies, PowerPoint presentations. TakeMyclassPro and select the details of your
ReplyDeleteThank you for sharing this.
ReplyDeleteIn chemical engineering, Process Design Engineering Course is the design of processes for desired physical and/or chemical transformation of materials.
Process Design Course in Maharashtra
ketu in 11th house is a good sign. It means that the natives will attain prosperity and everything they desire. It is good for materialistic people.
ReplyDeleteStressed over homework questions? Our experts got your back, from basic math to all the complicated ones. Go to our website SpiderEssay and select the details of your paper
ReplyDeleteStressed over homework questions? Our experts got your back, from basic math to all the complicated ones. Go to our website Spider Essay Online class takers and select the details of your paper
ReplyDeleteStressed over homework questions? Our experts got your back, from basic math to all the complicated ones. Go to our website Spider Essay Online class takers and select the details of your paper
ReplyDeleteGo to our website Take my proctor exam and select the details of your paper
Go to our website Take my exam and select the details of your paper
Go to our website Professionals do my online class and select the details of your paper
Go to our website Take my class and select the details of your paper
ReplyDeleteYour marks can improve if you choose our experts for Online Assignment Help at the last minutes. In addition to offering advice, we also go through a number of other important topics when writing assignments. You may achieve excellent score with our expert advice and assistance. You absolutely deserve the online Management Assignment Help offered by our qualified writers if you want to realize your goal.
Say hello to a revolutionary solution for capturing and reconstructing full-body motion, including Face and Hand Tracking. Animate 3D lets you turn videos into 3D animations for use in games, augmented/virtual reality, sports analysis and many more applications. make an animation
Delete"Empower your academic journey with the support of our online assignment writing experts at online assignment writing experts. Our dedicated team of professionals is committed to delivering top-tier assistance tailored to meet your unique assignment needs.
ReplyDelete"Excel in your academic journey with our top-notch online homework writing service! 📚 Our expert team of writers is dedicated to delivering custom, high-quality homework solutions tailored to your academic needs. From thorough research to flawless writing, we ensure excellence in every task. online Homework Writing Service
ReplyDelete"Navigate your Higher National Certificate (HNC) studies with confidence through our dedicated HNC assignment help services. Our expert team is committed to providing tailored assistance. HNC Assignment Help
ReplyDeleteThank you for the useful information on how to write Unit Test Classes for the Rest API service for POST HTTP calls, Most students also struggle with writing their assignments and taking help from assignment writing service in UK
ReplyDelete