0

I have the following Rest class and test class. The test class is working good in sandbox and failed in production. I have gone through numerous post and also followed to test with Mockclass as well. It failed in both the scenarios. I getting error as "Methods defined as TestMethod do not support Web service callouts Stack Trace". Any insights on what I am doing wrong will be helpful

REST Class

        @RestResource(urlMapping='/v1/products/*')
    global with Sharing class ProductManager {

        global class responseWrapper{
            global Id data_country{get;set;}
            global Id sf_productId{get;set;}
            global String productId{get;set;}
      //    global String productGroupId{get;set;}
            global String successMessage{get;set;}
        }

        public class updateProductJSON{
        public String sfProductId;
        public String productId;    
        public String product_name; 
        public String data_country; 
        public String product_category; 
        public String product_type; 
        public String product_listing;  
        public String revenue_type; 
        public Decimal price;   
        public String local_currency;   
        public Decimal local_currency_price;    
        public Decimal subscription_length; 
        public String status;   
        public String access;   
        public boolean require_quantity;
        public boolean prorated;
        public String description;  
        public String product_listing_id;   
        public String product_type_id;  
        public boolean sold_Internationally;
        public boolean sold_Individually;
        public String standard_peergroup;   
        public String demo_status;

       } 

    @httpget
        global static responseWrapper getCountryId(){        
            String countryId = RestContext.request.params.get('countryId');               
            Decimal countryId1 = decimal.valueOf(countryId);
            Id data_country = [SELECT ID FROM Country__c WHERE Country_ID__c =: countryId1].Id;
            responseWrapper response = new responseWrapper();
            response.data_country = data_country;
            return response;
        } 

    @httppost
        global static responseWrapper createProduct(String product_name,String data_country,String product_category,String product_type,String product_type_id,String product_listing,
                                       String revenue_type, Decimal price,String local_currency,Decimal local_currency_price, Decimal subscription_length,String status,
                                       String access,String product_listing_id,String description,Boolean require_quantity,Boolean prorated,Boolean sold_Internationally,
                                       Boolean sold_Individually,String demo_status,String standard_peergroup){
         String hgproductID;                               
         responseWrapper presponse = new responseWrapper(); 

         Product2 thisProduct = new Product2(Name=product_name,Data_Country__c=data_country,Family=product_category,Product_Type__c=product_type,Product_Type_ID__c=product_type_id,
                                        Product_Listing__c=product_listing,Revenue_Type__c=revenue_type,Price__c=price,Local_Currency__c=local_currency,Quantity_Required__c=require_quantity,
                                        Local_Currency_Price__c=local_currency_price,Subscription_Length__c=subscription_length,Status__c=status,ACCESS__c=access,
                                        Can_be_Prorated__c=prorated,Description=description,Product_Listing_ID__c=product_listing_id,Sold_Individually__c=sold_Individually,
                                        Sold_Internationally__c=sold_Internationally,Standard_Peer_Groups__c=standard_peergroup,Demo_Status__c=demo_status);

          if(!test.isrunningtest()){    //here is the change                    
                insert thisProduct;
                hgproductID = [SELECT Product_ID__c FROM Product2 WHERE Id=: thisProduct.Id].Product_ID__c;                                         
           }
            presponse.sf_productId = thisProduct.Id;
            presponse.productId = hgproductID;                               
            presponse.data_country =  data_country; 
            return presponse;
        }

    @HttpPut
        global static responseWrapper updateProduct(){
            RestRequest req = RestContext.request;
            String productId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);         
            String resstring = req.requestBody.toString();
            updateProductJSON result = (updateProductJSON)JSON.deserialize(resstring,updateProductJSON.class);
            responseWrapper upresponse = new responseWrapper();       
            Product2 up = [SELECT Id FROM Product2 WHERE Product_Id__c =: productId];
            Product2 uProduct = new Product2();
            uProduct.Id = up.Id;        
            uProduct.Name = result.product_name;
            uProduct.Data_Country__c = result.data_country;
            uProduct.Family = result.product_category;
            uProduct.Product_Type__c = result.product_type;
            uProduct.Product_Type_ID__c = result.product_type_id;
            uProduct.Product_Listing__c = result.product_listing;
            uProduct.Product_Listing_ID__c = result.product_listing_id;
            uProduct.Revenue_Type__c = result.revenue_type;
            uProduct.Price__c = result.price;
            uProduct.Local_Currency__c = result.local_currency;
            uProduct.Local_Currency_Price__c = result.local_currency_price;
            uProduct.Subscription_Length__c = result.subscription_length;
            uProduct.Status__c = result.status;
            uProduct.ACCESS__c = result.access;
            uProduct.Quantity_Required__c = result.require_quantity;
            uProduct.Can_be_Prorated__c = result.prorated;
            uProduct.Description = result.description;                
            uProduct.Sold_Individually__c = result.sold_Individually;
            uProduct.Sold_Internationally__c = result.sold_Internationally;
            uProduct.Standard_Peer_Groups__c = result.standard_peergroup;
            uProduct.Demo_Status__c = result.demo_status;

            if(!test.isrunningtest()){ //here is the change
                    try{
                        update uProduct;            
                        upresponse.sf_productId = uProduct.Id;
                        upresponse.successMessage = 'Product update completed';
                    }
                    catch(Exception e){            
                        upresponse.sf_productId = uProduct.Id;
                        upresponse.successMessage = e.getMessage();
                    }        
            }       

            return upresponse;
        }

    }

Test Class

@isTest(seeAllData=true)
public class ProductManager_Test {   


    public class updateProductJSON{
        public String sfProductId;
        public String productId;    //145777
        public String product_name; //DemoProduct14
        public String data_country; //a0d80000002IlyZ
        public String product_category; //Subscriptions
        public String product_type; //National
        public String product_listing;  //PayNet Mauritius Core
        public String revenue_type; //Subscription
        public Integer price;   //3500
        public String local_currency;   //USD
        public Integer local_currency_price;    //3500
        public Decimal subscription_length; //12
        public String status;   //Active
        public String access;   //All
        public boolean require_quantity;
        public boolean prorated;
        public String description;  //This is a rest product
        public String product_listing_id;   //12345
        public String product_type_id;  //67890
        public boolean sold_Internationally;
        public boolean sold_Individually;
        public String standard_peergroup;   //peergroup
        public boolean demo_product;

   }



    static testMethod void testDoGet() {
     Country__c cnty = new Country__c(Country_ID__c=123,Name='United States',Sponsor_Country__c='United States',Sponsor_Country_ID__c=12345);
     insert cnty;
    RestRequest req = new RestRequest(); 
    RestResponse res = new RestResponse();

    // pass the req and resp objects to the method     
    req.requestURI = 'https://cs23.salesforce.com/services/apexrest/v1/products?countryId=123';  
    req.httpMethod = 'GET';
    RestContext.request = req;
    RestContext.response = res;
    RestContext.request.params.put('countryId', '123');
    ProductManager.responseWrapper results = ProductManager.getCountryId();

  }

    static testMethod void testpostProduct(){
      //  StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
      //  mock.setStaticResource('CreateProduct');
      //  mock.setStatusCode(200);
      //  mock.setHeader('Content-Type', 'application/json');
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();                   
        RestContext.request = req;
        RestContext.response= res; 
        req.requestURI = '/services/apexrest/v1/products'; 
        req.httpMethod = 'POST';
        Test.startTest();
    //    Test.setMock(HttpCalloutMock.class, mock);
      ProductManager.responseWrapper results1 = ProductManager.createProduct('Test Class Product', 'a0d80000002IlyZ', 'Subscriptions', 'National', '67890', 'PayNet Mauritius Core',
                                                                                   'Subscription', 3500, 'USD', 3500, 12, 'Active', 'ALL', '12345', 'This is a rest product with response',
                                                                                          true, true, true, true, '1', 'peergroup'); 

        Test.stopTest();
    }

    static testMethod void testputProduct(){
        Product2 testProduct = new Product2(Name='Test Class Product',Family='Subscriptions',Data_Country__c='a0d80000002IlyZ',Product_Type__c='National',
                                           Product_Listing__c='PayNet Plus',Revenue_Type__c='On Delivery/RO',Price__c=3500,Local_Currency__c='USD',Local_Currency_Price__c=3500,
                                           Subscription_Length__c=12,Status__c='Active',ACCESS__c='ALL');
        insert testProduct;        
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();
        RestContext.request = req;
        RestContext.response= res;
        req.requestURI = '/services/apexrest/v1/products/'+testProduct.Product_ID__c; 
        req.httpMethod = 'PUT';
        updateProductJSON instance = new updateProductJSON();
    //     Product2 p2 = [SELECT Product_Id__c FROM Product2 WHERE Product_ID__c =: testProduct.Product_ID__c ];
        instance.product_name = 'DemoProductUpdate16';
    //     instance.productId = testProduct.Id;
        instance.data_country = 'a0d80000002IlyZ';
        instance.product_category = 'Subscriptions';
        instance.product_type = 'National';
        instance.product_listing = 'PayNet Mauritius Core';
        instance.revenue_type = 'Subscription';
        instance.price = 14500;
        instance.local_currency = 'USD';
        instance.local_currency_price = 15500;
        instance.subscription_length = 14;
        instance.status = 'Active';
        instance.access = 'ALL';
        instance.require_quantity = true;
        instance.prorated = true;
        instance.description = 'This is a rest product update';
        instance.product_listing_id = '12346';
        instance.product_type_id = '67890';
        instance.sold_Internationally = true;
        instance.sold_Individually = true;
        instance.standard_peergroup = 'peergroup';
        instance.demo_product = true;
        String testJSON = JSON.serialize(instance);
        req.requestBody = Blob.valueof(testJSON);  
        Test.startTest();        
        ProductManager.responseWrapper results2 = ProductManager.updateProduct();  
        Test.stopTest(); 
    } 
}

enter image description here

enter image description here

  • The mock statements are commented out in the test class. What error do you get when those lines are active? – David Cheng Jul 29 '17 at 20:02
  • This is the error i am getting. Methods defined as TestMethod do not support Web service callouts Stack Trace" – user28452 Jul 30 '17 at 1:47
1

For REST testing, you don't need to set up Mocks. However, you do need to execute GET(), POST() etc methods for your REST class to perform the HTTP request, and then parse the string from the response.

So in your testDoGet method,

req.requestURI = 'https://cs23.salesforce.com/services/apexrest/v1/products';
RestContext.request.params.put('countryId', '123');
RestContext.request = req;
RestContext.response = res;
ProductManager.GET();
String body = res.responseBody.toString();
ProductManager.responseWrapper result = (ProductManager.responseWrapper) JSON.deserialize(body, ProductManager.responseWrapper.class);
  • Thanks for your response. Request is working good but with the recommend line it is giving error as "Argument cannot be null" on the response. Screenshot attached. – user28452 Jul 30 '17 at 3:46
  • this is a different error, you should be opening a new post, @user28452 – glls Jul 31 '17 at 0:01
  • I was able to resolve by having if(!test.isrunningtest()){} in the REST Class. Updated the code – user28452 Jul 31 '17 at 4:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.