+ Start a Discussion
Angelina MuddamalleAngelina Muddamalle 

Test Class for HttpPost Method

Hi, I need to write a test class for my httppost method which uses json as input. i have tried implementing a test class using the HttpCalloutMock Interface but the apex class gets 0% code coverage in that case. Please suggest how can i go about this.

My apex class:
@RestResource(urlMapping='/abc/xyz/*')
global class MyClass{

    @HttpPost
    global static void updateMethod(){    
        try {        
            //get the json from the request
            RestRequest req1=RestContext.request;           
            String jsonInput= req1.requestBody.toString();       

            //create map for the obtained json input
            Map<String, Object> jsonMap = (Map<String, Object>) JSON.deserializeUntyped(jsonInput); 
            Id opptyId = String.valueOf(jsonMap.get('opportunity_SF_Id')) ;            
            
            //get the opportunity object       
            Sobject oppty = [SELECT id, description FROM opportunity WHERE id=:opptyId];
            //some more processing
            update oppty;        
        }catch(Exception e){
               System.debug('The following exception has occurred: ' + e.getMessage());
       }
    } 
}
karthikeyan perumalkarthikeyan perumal
Hello, 

Use Below Code, 
 
@istest
public class MyClassHTTPPost{

 static testMethod void  updateMethodTest(){

   opportunity  TestOpp=new opportunity ();
   date mydate = date.parse('12/27/2009');
   TestOpp.name='TestOpp1';
   TestOpp.StageName='Test';
   TestOpp.CloseDate=mydate ;
   insert TestOpp;
   MyClass reqst=new MyClass();
   String JsonMsg=JSON.serialize(reqst);
   Test.startTest();

   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;
    MyClass.updateMethod();
    update TestOpp;
    Test.stopTest();

   }
}

Hope this will help you.. 

Make Best ANSWER if its work for you. 

Thanks
karthik
 
Swaraj Behera 7Swaraj Behera 7
Hi Angelina,

I have Used your Rest api.Please find below Class and test class.

Rest Class:-
@RestResource(urlMapping='/abc/xyz/*')
global class RestAPIClass{

    @HttpPost
    global static DocWrapper updateMethod(){    
        try {        
            //get the json from the request
            RestRequest req1=RestContext.request;           
            String jsonInput= req1.requestBody.toString();
              DocWrapper response=new DocWrapper();       

            //create map for the obtained json input
            Map<String, Object> jsonMap = (Map<String, Object>) JSON.deserializeUntyped(jsonInput); 
            Id opptyId = String.valueOf(jsonMap.get('opportunity_SF_Id')) ;            
            
            //get the opportunity object       
            Sobject oppty = [SELECT id, description FROM opportunity WHERE id=:opptyId];
            //some more processing
            update oppty;  
            response.message='Opp Updated';
           
           return response;      
        }catch(Exception e){
        DocWrapper response=new DocWrapper();       
               System.debug('The following exception has occurred: ' + e.getMessage());
               response.message='Opp not updated';
               return response;
       }
       
     
    } 
      global class DocWrapper {          
          public String message;
     }
}

Test Class:-
 
@isTest
Public class RestAPIClassTest{
static testMethod void testDoPost(){
        
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();
        
      
    
        req.requestURI = '/services/apexrest/abc/xyz/';  
        req.httpMethod = 'POST';
        RestContext.request = req;
        RestContext.response = res;
        
        Test.startTest();
        RestAPIClass.DocWrapper  results = RestAPIClass.updateMethod();
        Test.stopTest();
        

    }   
    
  }

I Hope It Helps.

Thanks,
Swaraj Behera

Amit Chaudhary 8Amit Chaudhary 8
If you want to learn out Rest API please check below post
1) http://amitsalesforce.blogspot.com/2016/04/rest-api-in-salesforce-execute-rest-api.html

You test class should be like below
@IsTest
private class MyClassTest
{
    static testMethod void MyClassMethod()
    {
        Account acc = new Account();
        acc.Name='Test';
        acc.AccountNumber ='12345';
        insert acc;
        
		
		Opportunity mAWSUsage = new Opportunity( Name = 'mAWS Usage',
							  AccountId = acc.Id,
							  StageName = 'Negotiations',
							  CloseDate = System.today(),
							  Type = 'New Business - Add',
							  Amount = 555888555
						  );
		insert  mAWSUsage;
		
		
        RestRequest request = new RestRequest();
        request.requestUri ='/services/apexrest/abc/xyz/';
        request.httpMethod = 'POST';
		
        RestContext.request = request;
		
        MyClass.updateMethod();
		
        //System.assert(acc != null);
    }
}

 
Angelina MuddamalleAngelina Muddamalle

Thank you everyone..I figured this one out. Following is the solution that worked for my test class:

//method to test Update Opportunity and Product Details
    @isTest static void testUpdateOpptyProducts() {
        // Set up a test request
        Opportunity oppty = createTestRecord();
        
        String JSONMsg = '{"opportunity_SF_Id" : "'+oppty.Id +'","Amount":"123400.00"}';

        RestRequest req = new RestRequest();
        RestResponse res = new RestResponse();
        
        req.requestURI = '/services/apexrest/abc/xyz/';  //Request URL
        req.httpMethod = 'POST';//HTTP Request Type
        req.requestBody = Blob.valueof(JSONMsg);
        
        RestContext.request = req;
        RestContext.response= res;
        
        Test.startTest();
            MyClass.updateMethod();
        Test.StopTest();   
    }
    
    // Helper method to create test data
    static Locations__c createTestRecord() {
        // Create test record
        Account acc = new Account();
       acc.Name='Test';
       acc.AccountNumber ='12345';
       insert acc;

       Opportunity oppty = new Opportunity( Name = 'mAWS Usage', AccountId = acc.Id, StageName = 'Negotiations', CloseDate = System.today(), Type = 'New Business - Add', Amount = 555888555 ); 
insert oppty 
        return oppty ;
    }

Vennila Paramasivam 1Vennila Paramasivam 1
Thank you. This is working for me too.
Rohan TelangRohan Telang
@Angelina Muddamalle- Thank you so much ... This Test Class really covered my coverage.