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
SIVA KUMAR 507SIVA KUMAR 507 

Hey Guys I need t test class for the below code please guy help me

Apex Class:
_________
@RestResource(urlMapping='/v1/KnowledgeArticles/*')
global with sharing class KnowledgeMigrationService {
    @HttpPost
    global static String createArticle(String articleJsonStr) {
    Knowledge__kav article = (Knowledge__kav)System.JSON.deserialize(EncodingUtil.urlDecode(articleJsonStr,'UTF-8'), Knowledge__kav.class);
        List<Knowledge__kav> articles = [SELECT Id, PublishStatus, Body__c, Title, UrlName, ArticleNumber, KnowledgeArticleId FROM Knowledge__kav WHERE UrlName =: article.UrlName];
        if(articles.Size() == 0) {
            article.Id = null;
            insert article;
            
            return 'New article created';
        }
        else if(articles[0].PublishStatus == 'Draft') {
      article.Id = articles[0].Id;
            update article; 
            
            return 'Existing draft status article updated';
        }
        else if(articles[0].PublishStatus == 'Online') {
            String id = KbManagement.PublishingService.editOnlineArticle(articles[0].KnowledgeArticleId, false);
            
            List<Knowledge__kav> articles2 = [SELECT Id, PublishStatus, Body__c, Title, UrlName, ArticleNumber, KnowledgeArticleId FROM Knowledge__kav WHERE UrlName =: article.UrlName AND PublishStatus = 'Draft'];
      article.Id = articles2[0].Id;
            update article;
            
            KbManagement.PublishingService.publishArticle(articles2[0].KnowledgeArticleId, false);
            
            return 'Existing published status article updated';
        }
        else if(articles[0].PublishStatus == 'Archived') {
            String id = KbManagement.PublishingService.editArchivedArticle(articles[0].KnowledgeArticleId);
            
            List<Knowledge__kav> articles2 = [SELECT Id, PublishStatus, Body__c, Title, UrlName, ArticleNumber, KnowledgeArticleId FROM Knowledge__kav WHERE UrlName =: article.UrlName AND PublishStatus = 'Draft'];
      article.Id = articles2[0].Id;
            update article; 
            
            KbManagement.PublishingService.publishArticle(articles2[0].KnowledgeArticleId, false);
            KbManagement.PublishingService.archiveOnlineArticle(articles2[0].KnowledgeArticleId, null);
            
             return 'Existing archived status article updated';
        }
        
        return 'success';
    }
}
Suraj Tripathi 47Suraj Tripathi 47

Hi Siva,

Your code is long and complicated so you can take reference from my code.

@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;
    }
  }


//Test Class

@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';
   
   List lstcon=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();
   
   }
 }
 

And

public class UtiityClassl{
public cls_data[] data;
public class cls_data {
public String customerName;
public String Id;
public String opportunityId;
public String Status;
public String Value;
}
public static UtilityClass parse(String json){
return (UtilityClass) System.JSON.deserialize(json, UtilityClass.class);
}
}

//Test class 
@isTest 
public class UtiityClasslTest 
{
	
	 static testMethod void testEx1() 
	 {
		String jsonVal ='' ; 
		UtiityClassl.parse(jsonVal);
		
	 }
}


Hope it would help you.

Don't forget to mark it as Best Answer

​​​​​​​Thank You