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
Abhilash Mishra 13Abhilash Mishra 13 

How to cover this code block

I was not able to cover the code block based on document object..  my sample code is.
public class testcontroller{
public void method1(){ 
list<document>docs;
list<string>li=new list<string>()
  try{
                                 
                                   docs=[select id from document where name !=null'];
                                      
                                     }catch(Exception e){
                                         apexpages.addmessages(e);
                                      }
                        }


if(docs!null || !docs.isemprty()){
    for(document d:docs)
         li.add(d.name);

}

}
when writing test class i am not able to insert anty doucmet an always get docs as null
how can i cover if block.

Thanks
Abhilash

 
Stefan AbramiukStefan Abramiuk
Hi Abhilash,

Well here not simple case. Best option from technical point of view is to extract Select query to separate method and pass list of resutls to tested method. So in unit test you could create Document sObjects (only in memory)  and pass it to your method. You could even overrride this selector method and use it directly in tested method without passing any parametres.
 
public virutal class Testcontroller{
	private virtual List<Document> selectALLDocuments(){
		return [SELECT Id FROM Document WHERE Name !=null];
	}

	public void method1(){ 
		list<document>docs;
		list<string>li=new list<string>()
		try{
			docs=selectALLDocuments();
		}catch(Exception e){
			apexpages.addmessages(e);
		}
	}
}

public class testOverridecontroller extends Testcontroller{
	private override List<Document> selectALLDocuments(){
		return new List<Documents>{new Document(), new....... ;
	}
}

 
AshlekhAshlekh
Hi,

 
@isTest
private class Test_DocumentEmailer {

  static Document document;

  static {

    document = new Document();
    document.Body = Blob.valueOf('Some Text');
    document.ContentType = 'application/pdf';
    document.DeveloperName = 'my_document';
    document.IsPublic = true;
    document.Name = 'My Document';
    document.FolderId = [select id from folder where name = 'My Test Docs'].id;
    insert document;

  }

  static testMethod void testDocumentEmailer() {

testcontroller c = new testcontroller();

    Test.startTest();
     c.method1();
    Test.stopTest(); 

  }
}

Please try this and let me know.

-Thanks
Ashlekh Gera
Abhilash Mishra 13Abhilash Mishra 13
Hi Ashlekh
    your code is working final but its not covering the codeblock the value is still null.