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
ManojKumar MuthuManojKumar Muthu 

Test class for case attachment & Query

Hi there,

Can someone help with test class for below two Apex class??

@RestResource(urlMapping='/CaseAttachment/*')
global with sharing class CaseAttachment{

@HttpGet
    global static List<Attachment> getCaseById() {
       RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String Id = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
          List<Attachment> result =  [Select id, Name, OwnerId, BodyLength, LastModifiedById, LastModifiedDate, ContentType, Body, Description, CreatedDate, CreatedById from Attachment where ParentId = :Id];
        return result;
        }
           
@HttpPost
  global static void doget(String type, String body, String ContentType, String ParentID ){
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String CaseName=req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        String doc=EncodingUtil.Base64Encode(req.requestBody);
         Attachment a = new Attachment();
            a.Name = type;
            a.Body = Blob.valueOf(body);           
            a.ContentType = ContentType;
            a.ParentId = 'Id';
                
        insert a;
        
    }
}

and-------------------------------------------------------------------------------------------------------

@RestResource(urlMapping='/QueryFilterStatus/*')
global with sharing class QueryFilterStatus{
    
    @HttpPost
    global static List<Case> dopostCase(String Owneremail, String Bugis, String Version, String accountid,String tracker,String priority,String contactEmail,String status,String CStatus,String subject, String Keyword) {
    List<Case> caseList = new List<Case>();
    String str='Select id, Case_Owner_Name__c, OwneEmail__c, Description, Subject, Case_Type__c, Code__c, Tracker__c, status, Version__c, type, priority, ContactEmail, ContactId, OwnerId, CaseNumber, CSM_ID__c, CUP_Phone__c, Call_Type__c, IsClosed from Case where accountid =\''+ accountid +'\'';
    
    if(String.isNotBlank(Owneremail))
    {
       str+=' AND OwneEmail__c=\''+ Owneremail+'\'';
    }
    if(String.isNotBlank(Bugis))
    {
       str+=' AND BugIs__c=\''+ Bugis+'\'';
    }
    if(String.isNotBlank(Version))
    {
       str+=' AND Version__c=\''+ Version+'\'';
    }
    
    if(String.isNotBlank(tracker))
    {
       str+=' AND Tracker__c =\''+ tracker+'\'';
    }
     if(String.isNotBlank(priority))
    {
       str+=' AND Priority=\''+ priority+'\'';
    }
     if(String.isNotBlank(contactEmail))
    {
       str+=' AND ContactEmail=\''+ contactEmail+'\'';
    }
     if(String.isNotBlank(status))
    {
       str+=' AND Status =\''+ status+'\'';
    }
    
    if(String.isNotBlank(CStatus))
    {
       str+=' AND CStatus__c=\''+ CStatus+'\'';
    }
    
    //if(String.isNotBlank(subject))
    //{
    //   str+=' AND Subject Like \''+ subject+'\'';
   // }
    
    //if(String.isNotBlank(description))
    //{
     //  str+=' AND Description Like \''+ description+'\'';
    //}
    if(String.isNotBlank(Keyword))
   {
      str+=' AND (Subject Like\'%'+ Keyword+'%\'';
      str+=' OR CaseNumber Like \'%'+ Keyword+'%\')';
   }  
   System.debug(str);
    caseList=Database.query(str);
    return caseList;
    
    
}
}



 
Best Answer chosen by ManojKumar Muthu
Raj VakatiRaj Vakati
@isTest
private class QueryFilterStatusTest {
    @isTest static void testCaseOne() {
    
	Test.startTest();
	
	 Profile pf= [Select Id from profile where Name='System Administrator']; 
        
        String orgId=UserInfo.getOrganizationId(); 
        String dateString=String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','') ;
        Integer RandomId=Integer.valueOf(Math.rint(Math.random()*1000000)); 
        String uniqueName=orgId+dateString+RandomId; 
        User uu=new User(firstname = 'ABC', 
                         lastName = 'XYZ', 
                         email = uniqueName + '@test' + orgId + '.org', 
                         Username = uniqueName + '@test' + orgId + '.org', 
                         EmailEncodingKey = 'ISO-8859-1', 
                         Alias = uniqueName.substring(18, 23), 
                         TimeZoneSidKey = 'America/Los_Angeles', 
                         LocaleSidKey = 'en_US', 
                         LanguageLocaleKey = 'en_US', 
                         ProfileId = pf.Id
                        ); 
        
        
        insert uu;
		
		
		System.runAs(uu){

    //create account
    Account acc = new Account();
    //enter details  
    acc.Name = 'Test Account';
    insert acc;
  
  Contact con=new Contact(
            FirstName='fname',
            LastName = 'lname',
			AccountId= acc.Id , 
            Email = 'test@gmail.com',
            Phone = '9743800309'); 
        insert con; 
    
    //create case
    Case c = new Case();
    //enter details
    c.AccountId = acc.Id;
	
	c.Description='demo';
	c.Subject='testing';
	c.Case_Type__c='Demo';
	c.Code__c='1232';
	c.ContactId = con.id;
	c.Tracker__c='1212';
c.Version__c ='1'; 
c.priority ='High';
 CSM_ID__c='asdasd'; 
 c.CUP_Phone__c='123123123';
c.Call_Type__c='Escalation';
c.IsClosed= false ;
    c.Type = 'My Type';
    c.Origin = 'My Origin';
    c.Status = 'My Status';
    insert c;
	
	Attachment attach=new Attachment();   	
    	attach.Name='Test';
    	Blob bodyBlob=Blob.valueOf('Testing Body of Attachment');
    	attach.body=bodyBlob;
        attach.parentId=c.id;
        insert attach;
	

  
	
	
	
	
	  RestRequest req1 = new RestRequest(); 
   RestResponse res1 = new RestResponse();
   
   //String JsonMsg=JSON.serialize([Select Id from Case]);

    req1.requestURI = '/services/apexrest/QueryFilterStatus/';  //Request URL
    //req.requestBody = Blob.valueof(JsonMsg);
	 req1.httpMethod = 'POST';
    RestContext.request = req1;
    RestContext.response= res1;
    CaseAttachment.dopostCase(uu.email,'demo', '1', acc.Id,'1212','High','demo@gmail.com','My Status','My Status','testing', 'testing');
    Test.stopTest();
	
	
    
   
		}
	
	
    }
    
}

 

All Answers

Raj VakatiRaj Vakati
Here is the code
 
@isTest
private class CaseAccountidTest {
    @isTest static void testCaseOne() {
    
	Test.startTest();
	
	

    //create account
    Account acc = new Account();
    //enter details  
    acc.Name = 'Test Account';
    insert acc;
  
    
    //create case
    Case c = new Case();
    //enter details
    c.AccountId = acc.Id;
    c.Type = 'My Type';
    c.Origin = 'My Origin';
    c.Status = 'My Status';
    insert c;
	
	Attachment attach=new Attachment();   	
    	attach.Name='Test';
    	Blob bodyBlob=Blob.valueOf('Testing Body of Attachment');
    	attach.body=bodyBlob;
        attach.parentId=c.id;
        insert attach;
	

   RestRequest req = new RestRequest(); 
   RestResponse res = new RestResponse();

    req.requestURI = '/services/apexrest/CaseAttachment/'+c.accountId;  //Request URL
    req.requestBody = Blob.valueof(JsonMsg);
    RestContext.request = req;
    RestContext.response= res;
    CaseAccountid.getCaseById();
	
	
	
	
	  RestRequest req1 = new RestRequest(); 
   RestResponse res1 = new RestResponse();
   
   //String JsonMsg=JSON.serialize([Select Id from Case]);

    req1.requestURI = '/services/apexrest/CaseAttachment/';  //Request URL
    //req.requestBody = Blob.valueof(JsonMsg);
	 req1.httpMethod = 'POST';
    RestContext.request = req1;
    RestContext.response= res1;
    CaseAttachment.doget('pdf','aaaaaaaaaaaaaaaaa','pdf',c.Id);
    Test.stopTest();
	
	
    Test.stopTest();

   
	
	
	
    }
    
}

 
Raj VakatiRaj Vakati
Seconf class

 
@isTest
private class CaseAccountidTest {
    @isTest static void testCaseOne() {
    
	Test.startTest();
	
	 Profile pf= [Select Id from profile where Name='System Administrator']; 
        
        String orgId=UserInfo.getOrganizationId(); 
        String dateString=String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','') ;
        Integer RandomId=Integer.valueOf(Math.rint(Math.random()*1000000)); 
        String uniqueName=orgId+dateString+RandomId; 
        User uu=new User(firstname = 'ABC', 
                         lastName = 'XYZ', 
                         email = uniqueName + '@test' + orgId + '.org', 
                         Username = uniqueName + '@test' + orgId + '.org', 
                         EmailEncodingKey = 'ISO-8859-1', 
                         Alias = uniqueName.substring(18, 23), 
                         TimeZoneSidKey = 'America/Los_Angeles', 
                         LocaleSidKey = 'en_US', 
                         LanguageLocaleKey = 'en_US', 
                         ProfileId = pf.Id
                        ); 
        
        
        insert uu;
		
		
		System.runAs(uu){

    //create account
    Account acc = new Account();
    //enter details  
    acc.Name = 'Test Account';
    insert acc;
  
  Contact con=new Contact(
            FirstName='fname',
            LastName = 'lname',
			AccountId= acc.Id , 
            Email = 'test@gmail.com',
            Phone = '9743800309'); 
        insert con; 
    
    //create case
    Case c = new Case();
    //enter details
    c.AccountId = acc.Id;
	
	c.Description='demo';
	c.Subject='testing';
	c.Case_Type__c='Demo';
	c.Code__c='1232';
	c.ContactId = con.id;
	c.Tracker__c='1212';
c.Version__c ='1'; 
c.priority ='High';
 CSM_ID__c='asdasd'; 
 c.CUP_Phone__c='123123123';
c.Call_Type__c='Escalation';
c.IsClosed= false ;
    c.Type = 'My Type';
    c.Origin = 'My Origin';
    c.Status = 'My Status';
    insert c;
	
	Attachment attach=new Attachment();   	
    	attach.Name='Test';
    	Blob bodyBlob=Blob.valueOf('Testing Body of Attachment');
    	attach.body=bodyBlob;
        attach.parentId=c.id;
        insert attach;
	

  
	
	
	
	
	  RestRequest req1 = new RestRequest(); 
   RestResponse res1 = new RestResponse();
   
   //String JsonMsg=JSON.serialize([Select Id from Case]);

    req1.requestURI = '/services/apexrest/CaseAttachment/';  //Request URL
    //req.requestBody = Blob.valueof(JsonMsg);
	 req1.httpMethod = 'POST';
    RestContext.request = req1;
    RestContext.response= res1;
    CaseAttachment.dopostCase(uu.email,'demo', '1', acc.Id,'1212','High','demo@gmail.com','My Status','My Status','testing', 'testing');
    Test.stopTest();
	
	
    
   
		}
	
	
    }
    
}

 
Raj VakatiRaj Vakati
@isTest
private class QueryFilterStatusTest {
    @isTest static void testCaseOne() {
    
	Test.startTest();
	
	 Profile pf= [Select Id from profile where Name='System Administrator']; 
        
        String orgId=UserInfo.getOrganizationId(); 
        String dateString=String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','') ;
        Integer RandomId=Integer.valueOf(Math.rint(Math.random()*1000000)); 
        String uniqueName=orgId+dateString+RandomId; 
        User uu=new User(firstname = 'ABC', 
                         lastName = 'XYZ', 
                         email = uniqueName + '@test' + orgId + '.org', 
                         Username = uniqueName + '@test' + orgId + '.org', 
                         EmailEncodingKey = 'ISO-8859-1', 
                         Alias = uniqueName.substring(18, 23), 
                         TimeZoneSidKey = 'America/Los_Angeles', 
                         LocaleSidKey = 'en_US', 
                         LanguageLocaleKey = 'en_US', 
                         ProfileId = pf.Id
                        ); 
        
        
        insert uu;
		
		
		System.runAs(uu){

    //create account
    Account acc = new Account();
    //enter details  
    acc.Name = 'Test Account';
    insert acc;
  
  Contact con=new Contact(
            FirstName='fname',
            LastName = 'lname',
			AccountId= acc.Id , 
            Email = 'test@gmail.com',
            Phone = '9743800309'); 
        insert con; 
    
    //create case
    Case c = new Case();
    //enter details
    c.AccountId = acc.Id;
	
	c.Description='demo';
	c.Subject='testing';
	c.Case_Type__c='Demo';
	c.Code__c='1232';
	c.ContactId = con.id;
	c.Tracker__c='1212';
c.Version__c ='1'; 
c.priority ='High';
 CSM_ID__c='asdasd'; 
 c.CUP_Phone__c='123123123';
c.Call_Type__c='Escalation';
c.IsClosed= false ;
    c.Type = 'My Type';
    c.Origin = 'My Origin';
    c.Status = 'My Status';
    insert c;
	
	Attachment attach=new Attachment();   	
    	attach.Name='Test';
    	Blob bodyBlob=Blob.valueOf('Testing Body of Attachment');
    	attach.body=bodyBlob;
        attach.parentId=c.id;
        insert attach;
	

  
	
	
	
	
	  RestRequest req1 = new RestRequest(); 
   RestResponse res1 = new RestResponse();
   
   //String JsonMsg=JSON.serialize([Select Id from Case]);

    req1.requestURI = '/services/apexrest/QueryFilterStatus/';  //Request URL
    //req.requestBody = Blob.valueof(JsonMsg);
	 req1.httpMethod = 'POST';
    RestContext.request = req1;
    RestContext.response= res1;
    CaseAttachment.dopostCase(uu.email,'demo', '1', acc.Id,'1212','High','demo@gmail.com','My Status','My Status','testing', 'testing');
    Test.stopTest();
	
	
    
   
		}
	
	
    }
    
}

 
This was selected as the best answer
ManojKumar MuthuManojKumar Muthu
Hi raj,

when I run a test below the error i am getting for the first test classs,
Class.System.EncodingUtil.base64Encode: line 10, column 1
Class.CaseAttachment.doget: line 18, column 1
Class.CaseAttachment1Test.testCaseAttachment1One: line 55, column 1
Raj VakatiRaj Vakati
Give me CaseAttachment1Test class 
ManojKumar MuthuManojKumar Muthu
Here it is ,


@RestResource(urlMapping='/CaseAttachment/*')
global with sharing class CaseAttachment{

@HttpGet
    global static List<Attachment> getCaseById() {
       RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String Id = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
          List<Attachment> result =  [Select id, Name, OwnerId, BodyLength, LastModifiedById, LastModifiedDate, ContentType, Body, Description, CreatedDate, CreatedById from Attachment where ParentId = :Id];
        return result;
        }
           
@HttpPost
  global static void doget(String type, String body, String ContentType, String ParentID ){
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String CaseName=req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        String doc=EncodingUtil.Base64Encode(req.requestBody);
         Attachment a = new Attachment();
            a.Name = type;
            a.Body = Blob.valueOf(body);           
            a.ContentType = ContentType;
            a.ParentId = 'Id';
                
        insert a;
        
    }


________________________________________________________________________________________________________________

@isTest
private class CaseAttachment1Test {
    @isTest static void testCaseAttachment1One() {
    
    Test.startTest();
    
    

    //create account
    Account acc = new Account();
    //enter details  
    acc.Name = 'Test Account';
    insert acc;
  
    
    //create case
    Case c = new Case();
    //enter details
    c.AccountId = acc.Id;
    c.Type = 'My Type';
    c.Origin = 'My Origin';
    c.Status = 'My Status';
    insert c;
    
    Attachment attach=new Attachment();     
        attach.Name='Test';
        Blob bodyBlob=Blob.valueOf('Testing Body of Attachment');
        attach.body=bodyBlob;
        attach.parentId=c.id;
        insert attach;
    

   RestRequest req = new RestRequest(); 
   RestResponse res = new RestResponse();

    req.requestURI = '/services/apexrest/CaseAttachment/'+c.accountId;  //Request URL
    req.requestBody = Blob.valueof('JsonMsg');
    RestContext.request = req;
    RestContext.response= res;
    CaseAttachment.getCaseById();
    
    
    
    
      RestRequest req1 = new RestRequest(); 
   RestResponse res1 = new RestResponse();
   
   //String JsonMsg=JSON.serialize([Select Id from Case]);

    req1.requestURI = '/services/apexrest/CaseAttachment/';  //Request URL
    //req.requestBody = Blob.valueof(JsonMsg);
     req1.httpMethod = 'POST';
    RestContext.request = req1;
    RestContext.response= res1;
    CaseAttachment.doget('pdf','aaaaaaaaaaaaaaaaa','pdf',c.Id);
    Test.stopTest();
    
    
    Test.stopTest();

   
    
    
    
    }
    
}
Raj VakatiRaj Vakati
Try this
 
@isTest
private class CaseAttachment1Test {
    @isTest static void testCaseAttachment1One() {
    
    Test.startTest();
    
    

    //create account
    Account acc = new Account();
    //enter details  
    acc.Name = 'Test Account';
    insert acc;
  
    
    //create case
    Case c = new Case();
    //enter details
    c.AccountId = acc.Id;
    c.Type = 'My Type';
    c.Origin = 'My Origin';
    c.Status = 'My Status';
    insert c;
    
    Attachment attach=new Attachment();     
        attach.Name='Test';
        Blob bodyBlob=Blob.valueOf('Testing Body of Attachment');
        attach.body=bodyBlob;
        attach.parentId=c.id;
        insert attach;
    

   RestRequest req = new RestRequest(); 
   RestResponse res = new RestResponse();

    req.requestURI = '/services/apexrest/CaseAttachment/'+c.accountId;  //Request URL
    req.requestBody = Blob.valueof('JsonMsg');
	     req.httpMethod = 'GET';

    RestContext.request = req;
    RestContext.response= res;
    CaseAttachment.getCaseById();
    
    
    
    
      RestRequest req1 = new RestRequest(); 
   RestResponse res1 = new RestResponse();
   
   //String JsonMsg=JSON.serialize([Select Id from Case]);

    req1.requestURI = '/services/apexrest/CaseAttachment/';  //Request URL
    //req.requestBody = Blob.valueof(JsonMsg);
     req1.httpMethod = 'POST';
    RestContext.request = req1;
    RestContext.response= res1;
    CaseAttachment.doget('pdf','aaaaaaaaaaaaaaaaa','application/pdf',c.Id);
    Test.stopTest();
    
    
    Test.stopTest();

   
    
    
    
    }
    
}

 
ManojKumar MuthuManojKumar Muthu
Code coverage is 64%,

this part is alone is not covering in apex class

Attachment a = new Attachment();
            a.Name = name;
            a.Body = Blob.valueOf(body);           
            a.ContentType = ContentType;
            a.ParentId = 'Id';
                
        insert a;