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
RajaMohanRajaMohan 

How to cover the test coverage?

Hi Folks,

 

I am unable to cover the parts which is marked in red in test coverage. Please help me in covering these parts. It is very urgernt.

 

 

public PageReference EmailQuote(){

try
{

PageReference pcd = Page.esc_Quote;
pcd.getParameters().put('id',Oppr.id);
Blob pdfBlob = pcd.getContent();

Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
String [] toAddresses = new String[] {SearchTo};
String [] toCC = new String[] {SearchCC};
String [] toBCC = new String[] {SearchBCC};
str1=SearchBody.replaceAll('\n','<br/>');

if(Acc.RecordTypeId=='0122000000058UW' || Acc.RecordTypeId=='01220000000HS25'){
Contact cc=[select id,name,Email from contact where id=:oppr.contact__c];
if(cc.Email != null){
email.setTargetObjectId(cc.Id);
email.setSubject(SearchSubject);
email.setHtmlBody(str1);

if(SearchCC!=''){
email.setCcAddresses(toCC);
}
if(SearchBCC!=''){
email.setBccAddresses(toBCC);
}
email.setSaveAsActivity(true);

// Create an email attachment
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName('ES_'+ Oppr.Quote_Number__c+'-'+ Oppr.Quote_Version__c + '.pdf');
efa.setBody(pdfBlob); //attach the PDF
email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});

//Create an event.
Task myTask = new Task();
myTask.WhatId = Oppr.Id;
myTask.WhoId = cc.Id;
myTask.IsReminderSet = true;
myTask.ReminderDateTime = System.Today();
myTask.ActivityDate = System.Today();
myTask.Description = SearchBody;
myTask.Subject = SearchSubject;
myTask.OwnerId = Usr.Id;
myTask.Status = 'Completed';

Insert myTask;
}

else{
email.setSaveAsActivity(false);
email.setTargetObjectId(usr.Id);
email.setSubject('No Email to send the Quotation');
email.setHtmlBody('Dear '+usr.Name+', No Email ID found into the Contact to send the Quotation.');
}

}

if(Acc.RecordTypeId=='0122000000058cV'){

//email.setTargetObjectId(Con.Id);
email.setSubject(SearchSubject);
email.setHtmlBody(str1);

email.setToAddresses(toAddresses);

if(SearchCC!=''){
email.setCcAddresses(toCC);
}
if(SearchBCC!=''){
email.setBccAddresses(toBCC);
}
email.setSaveAsActivity(true);

//Create an email attachment
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName('ES_'+ Oppr.Quote_Number__c+'-'+ Oppr.Quote_Version__c + '.pdf');
efa.setBody(pdfBlob); //attach the PDF
email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});

//Create an event.
Task myTask = new Task();
myTask.WhatId = Oppr.Id;
myTask.WhoId = con.Id;
myTask.IsReminderSet = true;
myTask.ReminderDateTime = System.Today();
myTask.ActivityDate = System.Today();
myTask.Description = SearchBody;
myTask.Subject = SearchSubject;
myTask.OwnerId = Usr.Id;
myTask.Status = 'Completed';

Insert myTask;

}

Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

Pagereference OppPage = new ApexPages.StandardController(Oppr).view();
opppage.setredirect(true);
return OppPage;
}
catch(Exception e){
System.debug('ERROR:' + e);
return null;
}

}

 

 

 

IvarIvar

Hi Raja.

 

This code I guess is not being covered since you are hardcoding a reference to specific Ids. Preferrably you would call for the RecordType ids by name and use the retrieved ids instead, then you won't get a conflict between Ids in your development and production orgs.

 

Something like:

 

 

RecordType r = [Select Id from RecordType where Name = 'RecordTypeBeingCheckedFor' and SObject = 'ObjectInQuestion' limit 1];

If( Acc.RecordTypeId == r.Id ){
     //do your thing and it should now be covered
}

 

 

The other solution would be to use a test condition to trigger the execution of the code. You would create a boolean variable in your class named something like "isTest", which default to false but you'd set to true in your test methods. Then you'd change your if conditions to this:

 

 

if(Acc.RecordTypeId=='0122000000058UW' || Acc.RecordTypeId=='01220000000HS25' || isTest){

 

 

That should also trigger the execution of the code block in question.

 

Hope this helps.

Regards,

Ivar

RajaMohanRajaMohan

Hi Ivar

 

Thanks for your reply. The test coverage is still the same. This is my full code.

 

 

public class SendEmailClass{

	public Opportunity oppr {get;set;}
	Account Acc;
	Contact con;
	Contact con2;
	User usr;
	OpportunityContactRole cRole;
	EmailTemplate Quote;
	EmailTemplate Invoice;
	RecordType r1;
	RecordType r2;
	RecordType r3;
	String SearchFrom;
	String SearchTo;
	String SearchUserEmail;
	String SearchCC;
	String SearchBCC;
	String SearchSubject;
	String SearchSubject1;
	String SearchBody;
	String SearchBody1;
	String str = '';
	string str1 = '';
	String str2 = '';
	public String view='';
	
	
	
       
	public SendEmailClass(ApexPages.StandardController Controller){
		
		
		Oppr = [select Name,Id,contact__c,AccountId,Owner.FirstName,Invoice_Number__c,Quote_Number__c,Quote_Version__c,CreatedBy.Id from Opportunity where Id=:ApexPages.currentPage().getParameters().get('id')];
        System.Debug('Opportunity Name is: '+Oppr.Name);
        usr = [Select Name,Id,Email from User where Id =:UserInfo.getUserId()];
                               
        Quote = [Select id,Subject,Body from EmailTemplate where id=:'00XP0000000LzHL'];
        System.Debug('Template Subject Is: '+Quote.Subject);
        Invoice = [Select id,Subject,Body from EmailTemplate where id=:'00XP0000000LzHV'];
        
        Acc = [Select Name,Id,PersonEmail,RecordTypeId from Account where Id=:oppr.AccountId];
        
        r1 = [Select Id from RecordType where SobjectType = 'Account' and Name = 'Business Account' Limit 1];
        r2 = [Select Id from RecordType where SobjectType = 'Account' and Name = 'Competitive' Limit 1];
        r3 = [Select Id from RecordType where SobjectType = 'Account' and Name = 'Person Account' Limit 1];
        
		if(Acc.RecordTypeId == r3.Id){
			try
			{
		con =[Select Name, Id,AccountId,Email from contact where AccountId=:Acc.Id];
		}catch(exception ex){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Please Add a contact Email to this Opportunity'+ex));
            }
		}
		
		if(Acc.RecordTypeId == r1.Id || Acc.RecordTypeId == r2.Id){
			try
			{
			cRole = [Select ContactId from OpportunityContactRole where OpportunityId=:Oppr.Id and IsPrimary=:True Limit 1];
			con2 = [Select Name, Id,AccountId,Email from contact where Id=:Crole.ContactId];
			}catch(exception ex){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Please Add a contact Role to this Opportunity'+ex));
            
            }
		}
			
		if(Acc.RecordTypeId == r3.Id){
			try
			{
		view = 'False';	
		SearchTo = con.Email;
		str = con.Name;
		}catch(exception ex){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Please Add a contact Email to this Opportunity'+ex));
            }
		}
		else{
			try{		
		view = 'True';	
		SearchTo = con2.Email;
		Oppr.Contact__c=Con2.Id;
		str = con2.Name;
		}catch(exception ex){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Please Add a contact Role to this Opportunity'+ex));
            }				
		}
		
		SearchFrom = usr.Email;
		SearchBCC = usr.Email;
		SearchSubject = Quote.Subject +' ' + Oppr.Quote_Number__c+'-'+ Oppr.Quote_Version__c + '.pdf';
		SearchSubject1 = Invoice.Subject + ' ' + Oppr.Invoice_Number__c + '.pdf';
		SearchBody = 'Dear' + '\n' + str + '\n' + '\n' + Quote.Body + '\n' + '\n' + 'Regards' + '\n' + usr.Name;
		SearchBody1 = 'Dear' + '\n' + str + '\n' + '\n' + Invoice.body + '\n' + '\n' + 'Regards' + '\n' + usr.Name;
			
	}
	
	public String getview(){
		return this.view;
	}
    
	public String getSearchFrom() {
    	return this.SearchFrom;
    }
    
    
    public void setSearchFrom(String Search) {    	
    	this.SearchFrom=Search;	
    }
    
    public String getSearchTo() {
    	return this.SearchTo;
    }
    
    public void setSearchTo(String Search) {    	
    	this.SearchTo=Search;	
    }
    
    public String getSearchUserEmail() {
    	return this.SearchUserEmail;
    }
    
    public void setSearchUserEmail(String Search) {    	
    	this.SearchUserEmail=Search;	
    }
    
    public String getSearchCC() {
    	return this.SearchCC;
    }
    
    public void setSearchCC(String Search) {    	
    	this.SearchCC=Search;	
    }
    
    public String getSearchBCC() {
    	return this.SearchBCC;
    }
    
    public void setSearchBCC(String Search) {    	
    	this.SearchBCC=Search;	
    }
    
    public String getSearchSubject() {
    	return this.SearchSubject;
    }
    
    public void setSearchSubject(String Search) {    	
    	this.SearchSubject=Search;
    }
    	
    public String getSearchSubject1(){
    	return this.SearchSubject1;
    }
    
    public void setSearchSubject1(String Search) {    	
    	this.SearchSubject1=Search;	
    		
    }
    
    public String getSearchBody() {
    	return this.SearchBody;
    }
    
    public void setSearchBody(String Search) {    	
    	this.SearchBody=Search;	
    }
    
    public String getSearchBody1() {
    	return this.SearchBody1;
    }
    
    public void setSearchBody1(String Search) {    	
    	this.SearchBody1=Search;	
    }
    
   public PageReference EmailQuote(){
   	
   	try
    {
    
      PageReference pcd = Page.esc_Quote;
      pcd.getParameters().put('id',Oppr.id);
      Blob pdfBlob = pcd.getContent();
                  
      Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();      
      String [] toAddresses = new String[] {SearchTo};
      String [] toCC = new String[] {SearchCC};
      String [] toBCC = new String[] {SearchBCC};
	  str1=SearchBody.replaceAll('\n','<br/>');
	  
      if(Acc.RecordTypeId == r1.Id || Acc.RecordTypeId == r2.Id){
      	Contact cc=[select id,name,Email from contact where id=:oppr.contact__c];
      	      if(cc.Email != null){     
		      email.setTargetObjectId(cc.Id);
		      email.setSubject(SearchSubject);
		      email.setHtmlBody(str1);
		      
		      if(SearchCC!=''){
		      email.setCcAddresses(toCC);
		      }
		      if(SearchBCC!=''){
		      email.setBccAddresses(toBCC);
		      }
		      email.setSaveAsActivity(true);
		      		      
		      	  // Create an email attachment
			      Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
			      efa.setFileName('ES_'+ Oppr.Quote_Number__c+'-'+ Oppr.Quote_Version__c + '.pdf'); 
			      efa.setBody(pdfBlob); //attach the PDF
			      email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
			      
			        //Create an event.
			        Task myTask = new Task();
			        myTask.WhatId = Oppr.Id;
			        myTask.WhoId = cc.Id;
			        myTask.IsReminderSet = true;
			        myTask.ReminderDateTime = System.Today();
			        myTask.ActivityDate = System.Today();
			        myTask.Description = SearchBody;
			        myTask.Subject = SearchSubject;
			        myTask.OwnerId = Usr.Id;
			        myTask.Status = 'Completed';
			        
			        Insert myTask;			      	      		
		      }
		      
		      else{
		        email.setSaveAsActivity(false);	
		        email.setTargetObjectId(usr.Id);
		        email.setSubject('No Email to send the Quotation');
		        email.setHtmlBody('Dear '+usr.Name+', No Email ID found into the Contact to send the Quotation.');
		      }  
		      
      }
      
      if(Acc.RecordTypeId == r3.Id){
		  	  
		  		//email.setTargetObjectId(Con.Id);
		        email.setSubject(SearchSubject);
		        email.setHtmlBody(str1);
		        
		      	email.setToAddresses(toAddresses);
		     	
		      	if(SearchCC!=''){
		      	email.setCcAddresses(toCC);
		      	}
		      	if(SearchBCC!=''){
		      	email.setBccAddresses(toBCC);
		      	}
		        email.setSaveAsActivity(true);
		        
		          //Create an email attachment
			      Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
			      efa.setFileName('ES_'+ Oppr.Quote_Number__c+'-'+ Oppr.Quote_Version__c + '.pdf'); 
			      efa.setBody(pdfBlob); //attach the PDF
			      email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
			      
			      //Create an event.
			        Task myTask = new Task();
			        myTask.WhatId = Oppr.Id;
			        myTask.WhoId = con.Id;
			        myTask.IsReminderSet = true;
			        myTask.ReminderDateTime = System.Today();
			        myTask.ActivityDate = System.Today();
			        myTask.Description = SearchBody;
			        myTask.Subject = SearchSubject;
			        myTask.OwnerId = Usr.Id;
			        myTask.Status = 'Completed';
			        
			        Insert myTask; 
		        		  		
      }
      
      Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
      
      Pagereference OppPage = new ApexPages.StandardController(Oppr).view();
      opppage.setredirect(true);
      return OppPage;
    }catch(Exception e){
    System.debug('ERROR:' + e);
    return null;
    }

  }
  
  public PageReference EmailInvoice(){
   	
   	try
    {

      PageReference pcd = Page.esc_Invoice;
      pcd.getParameters().put('id',Oppr.id);
      Blob pdfBlob = pcd.getContent();
      str2=SearchBody1.replaceAll('\n','<br/>');
      
      Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();      
      String [] toAddresses = new String[] {SearchTo};
      String [] toCC = new String[] {SearchCC};
      String [] toBCC = new String[] {SearchBCC}; 
           
      if(Acc.RecordTypeId == r1.Id || Acc.RecordTypeId == r2.Id){  
      	Contact cc=[select id,name,Email from contact where id=:oppr.contact__c];
		      if(cc.Email != null){     
		      email.setTargetObjectId(cc.Id);
		      email.setSubject(SearchSubject1);
		      email.setHtmlBody(str2);
		      
		      if(SearchCC!=''){
		      email.setCcAddresses(toCC);
		      }
		      if(SearchBCC!=''){
		      email.setBccAddresses(toBCC);
		      }
		      email.setSaveAsActivity(true);		      
		      
		      	  // Create an email attachment
			      Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
			      efa.setFileName('ES_'+Oppr.Invoice_Number__c + '.pdf'); 
			      efa.setBody(pdfBlob); //attach the PDF
			      email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
			      
			      //Create an event.
			        Task myTask = new Task();
			        myTask.WhatId = Oppr.Id;
			        myTask.WhoId = cc.Id;
			        myTask.IsReminderSet = true;
			        myTask.ReminderDateTime = System.Today();
			        myTask.ActivityDate = System.Today();
			        myTask.Description = SearchBody1;
			        myTask.Subject = SearchSubject1;
			        myTask.OwnerId = Usr.Id;
			        myTask.Status = 'Completed';
			        
			        Insert myTask;			      	      		
		      }
		      
		      else{
		      email.setSaveAsActivity(false);	
		        email.setTargetObjectId(usr.Id);
		        email.setSubject('No Email to send the Quotation');
		        email.setHtmlBody('Dear '+usr.Name+', No Email ID found into the Contact to send the Quotation.');
		      }  
		      
      }
      
      if(Acc.RecordTypeId == r3.Id){
		  	  
		  		//email.setTargetObjectId(Con.Id);
		        email.setSubject(SearchSubject1);
		        email.setHtmlBody(str2);
		        email.setToAddresses(toAddresses);
		      	
		      	if(SearchCC!=''){
		      	email.setCcAddresses(toCC);
		     	}
		     	if(SearchBCC!=''){
		     	email.setBccAddresses(toBCC);
		      	}
		        email.setSaveAsActivity(true);
		        
		          // Create an email attachment
			      Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
			      efa.setFileName('ES_'+Oppr.Invoice_Number__c + '.pdf'); 
			      efa.setBody(pdfBlob); //attach the PDF
			      email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
			      
			      //Create an event.
			        Task myTask = new Task();
			        myTask.WhatId = Oppr.Id;
			        myTask.WhoId = con.Id;
			        myTask.IsReminderSet = true;
			        myTask.ReminderDateTime = System.Today();
			        myTask.ActivityDate = System.Today();
			        myTask.Description = SearchBody1;
			        myTask.Subject = SearchSubject1;
			        myTask.OwnerId = Usr.Id;
			        myTask.Status = 'Completed';
			        
			        Insert myTask;
      }
      
      Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
      
      Pagereference OppPage = new ApexPages.StandardController(Oppr).view();
      opppage.setredirect(true);
      return OppPage;
    }catch(Exception e){
    System.debug('ERROR:' + e);
    return null;
    }
    
}	  
 
 	private ApexPages.StandardController controller;
}

 

 

Thanks

Raj

IvarIvar

Hi again.

 

I don't see your test methods in there. Are you sure they work with accounts of all the record types mentioned, and thus enforce the execution of those code blocks?

 

Regards,

Ivar

Damien_Damien_

It seems to me that you are erroring and it is causing you to fall out of the function.

 

String [] toBCC = new String[] {SearchBCC};

Error seems to occur here.  You don't want your try/catch block to be over all that code.  It is meant for a specific spot that you think could error, and so that you can take the right actions if it does.

cloudcodercloudcoder

can you post your test methods? I'm a big fan of test suites vs. test cases which test your application more like how you actually use the app. Once you post the test methods I can give some pointers

RajaMohanRajaMohan

 

@isTest
private class Esc_Test {

    
    public static Account createAccount(){
    	RecordType r1 = [Select Id from RecordType where SobjectType = 'Account' and Name = 'Business Account' Limit 1];
    	
        List<User> UserOwner = [Select Name, Id, CurrencyIsoCode from User where  IsActive=true and CurrencyIsoCode = 'GBP' limit 1 ]; 
        Account acc = new Account(Name ='Apextest', OwnerId=UserOwner.get(0).Id, RecordTypeId=r1.Id);
        insert acc;
        return acc;
    }
   
    public static Account NewAccount(){
   		RecordType r2 = [Select Id from RecordType where SobjectType = 'Account' and Name = 'Person Account' Limit 1];
   		List<User> UserOwner = [Select Name, Id, CurrencyIsoCode from User where  IsActive=true and CurrencyIsoCode = 'GBP' limit 1 ];
   		Account a = new Account(FirstName='Arish',LastName='Khan',Person_Type__pc='Student',OwnerId=UserOwner.get(0).Id, RecordTypeId=r2.Id,PersonEmail='Test@test.com');
   		insert a;
   		return a;
   	
    } 
   
    public static Contact setupContact(){
		User UserOwner = [Select Name, Id from User where  IsActive=true limit 1];
		Account acc = createAccount();
		Contact Cont = new Contact(AccountId = acc.Id, FirstName='Test',Person_Type__c='Student',Email='test@test.com',LastName='Test1', Phone='012345678910');
		insert Cont;
		return cont;
    }
    
    public static Contact NewContact(){
		User UserOwner = [Select Name, Id from User where  IsActive=true limit 1];
		Account ac = NewAccount();
		Contact c  = new Contact(AccountId = ac.Id, FirstName='Test1',Person_Type__c='Student',Email='test@test.com',LastName='Test1', Phone='012345678910');
		insert c;
		return c;        	
    }
    
    public static Opportunity NewOppr(){
    	User UserOwner = [Select Name, Id from User where  IsActive=true limit 1];
    	Account aac = NewAccount();
    	Opportunity o = new Opportunity(VAT__c=15, Type='Consultancy',Margin_value__c=20, StageName='Coursed Booked', Payment_Terms__c='30 days from invoice', CurrencyIsoCode='GBP', OwnerId=UserOwner.Id, Name='apexmarketing', CloseDate=System.Today()+200, AccountId = aac.Id,Amount=12345);
    	insert o;
    	return o;
    }
    
    public static Opportunity setupOpportunity(){
		User UserOwner = [Select Name, Id from User where  IsActive=true limit 1]; 
		Account acc = createAccount();      
		Contact Cont = new Contact(AccountId = acc.Id, FirstName='Test',Person_Type__c='Student' ,LastName='Test1', Phone='012345678910');
		insert Cont;
		Opportunity oppr = new Opportunity(VAT__c=15, Type='Consultancy',Margin_value__c=20, StageName='Coursed Booked', Payment_Terms__c='30 days from invoice', CurrencyIsoCode='GBP', OwnerId=UserOwner.Id, Name='apexmarketing', CloseDate=System.Today()+200, AccountId = acc.Id);
		insert oppr;
		return oppr;  
    }   
        
	public static OpportunityContactRole setupOcr(){
		User UserOwner = [Select Name, Id from User where  IsActive=true limit 1];
		Account acc = createAccount();
		Contact cont = setupContact();
		Opportunity Oppr = setupOpportunity();
		
		OpportunityContactRole ocr = new OpportunityContactRole(ContactId=cont.Id,OpportunityId=Oppr.Id,Role='Producer',IsPrimary=True);
		insert ocr;
		return ocr;
	}

public static TestMethod void TestSendEmailClass(){ 

		Profile p=[select Id from profile where name='Standard User'];
		User usr=new User(alias='Cons', email='test@gmail.com',emailencodingkey='UTF-8',lastname='League',languagelocalekey='en_US',localesidkey='en_US',profileid=p.id,timezonesidkey='America/Los_Angeles',username='cons@gmail.com');
		System.runAs(usr)
		{
		
			Contact c = new Contact();
			c = setupContact();
			
			Opportunity newOpportunity = new Opportunity();
			newOpportunity = setupOpportunity();
			List<PricebookEntry> PriceBookId = [Select p.UnitPrice, p.ProductCode, p.Product2Id, p.Pricebook2Id, p.Name, p.IsActive, p.Id From PricebookEntry p where CurrencyIsoCode =: newOpportunity.CurrencyIsoCode and ProductCode= 'Full-time classroom course' and IsActive = True limit 2];
		
			OpportunityLineItem oppLineItem = new OpportunityLineItem( UnitPrice=100, PricebookEntryId=PriceBookId.get(0).Id, ServiceDate=System.Today(),Start_Date__c=System.Today(), End_Date__c=System.Today()+30,Quantity=1, OpportunityId=setupOpportunity().Id);
			
			insert oppLineItem; 
			newOpportunity.StageName='Closed Won';
			newOpportunity.Invoice_Number__c='09';
			newOpportunity.Quote_Version__c='2';
			update newOpportunity; 
			delete  oppLineItem;
			
			OpportunityContactRole cRole = new OpportunityContactRole(ContactID=c.Id,IsPrimary=True,OpportunityId=newOpportunity.Id,Role='Artist');
			insert cRole;
			delete cRole;
			
			Opportunity op = new Opportunity();
			op = NewOppr();
							   
			PageReference pageRef = Page.SendQuote;
			Test.setCurrentPageReference(pageRef);
			
			PageReference Ref = Page.SendInvoice;
			Test.setCurrentPageReference(Ref);  
			
			ApexPages.currentPage().getParameters().put('id',newOpportunity.id);
			ApexPages.StandardController sc = new ApexPages.StandardController(newOpportunity);
			SendEmailClass  controllerExtension = new SendEmailClass(sc);
			ApexPages.currentPage();
			
			SendEmailClass sec = new SendEmailClass(sc);
			
			sec.getView();
			sec.getSearchTo();
			sec.setSearchTo('a@gmail.com');
			sec.getSearchFrom();
			sec.setSearchFrom('b@gmail.com');
			sec.getSearchUserEmail();
			sec.setSearchUserEmail('c@gmail.com');
			sec.getSearchCC();
			sec.setSearchCC('d@gmail.com');
			sec.getSearchBCC();
			sec.setSearchBCC('e@gmail.com');
			sec.getSearchSubject();
			sec.setSearchSubject('Quotation');
			sec.getSearchSubject1();
			sec.setSearchSubject1('Invoice');
			sec.getSearchBody();
			sec.setSearchBody('Quotation Body');
			sec.getSearchBody1();
			sec.setSearchBody1('Invoice Body');
			
			Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
			String[] toAddresses = new String[]{'arish@consleague.com'};
			String [] toCC = new String[]{'arish1@consleague.com'};
			String [] toBcc = new String[]{'arish2@consleague.com'};
			email.setSubject('test');
			email.setHtmlBody('Hello, this a test email body. for testing purposes only. Bye');
			email.setToAddresses(toAddresses); 
			email.setCcAddresses(toCC);
			email.setBCcAddresses(toBcc); 
			email.setTargetObjectId(c.Id);
			
			Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
			
			Task myTask = new Task();
			myTask.WhatId = newOpportunity.Id;
			myTask.WhoId = c.Id;
			myTask.IsReminderSet = true;
			myTask.ReminderDateTime = System.Today();
			myTask.ActivityDate = System.Today();
			myTask.Description = 'Test data';
			myTask.Subject = 'Test subject';
			myTask.Status = 'Completed';  
			
			insert myTask;
			
			sec.EmailQuote();
			sec.EmailInvoice();

		}   
	}

}

 

This is test class for my Class.

 

thanks

 

surya143surya143

 

   
stuDetailController (Code Covered: 75%)
 line source
 1  public class stuDetailController
 2  {
 3   public student__c students{get;set;}
 4   public string stuID{get;set;}
 5  
 6   public stuDetailController()
 7   {
 8   students = new student__c();
 9   stuID = ApexPages.CurrentPage().getParaMeters().get('id');
 10  
 11  
 12   students = [select id,First_Name__c,Class__C,Sex__C,Wife_Name__c,Have_Vehicle__C,Married__C,
 13   Name,DOB__c,Email__c from student__c where id =: stuID];
 14  
 15   }
 16  
 17   public void sendpdf(){
 18  
 19   if(students.Email__c != null){
 20  
 21   Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
 22   List<String> addresses = new List<String>();
 23   addresses.add(students.Email__C);
 24   system.debug('###'+students.Email__C);
 25   email.setToAddresses(addresses);
 26   email.setSubject('Testing Email');
 27   email.setHTMLBody('Hello');
 28  
 29  
 30   PageReference pdf = Page.studentdetail;
 31   pdf.getParameters().put('id',students.id);
 32   system.debug('###'+pdf);
 33   pdf.setRedirect(true);
 34  
 35   Blob b = pdf.getContentAsPdf();
 36   system.debug('###'+b);
 37   Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
 38  
 39   efa.setFileName('attachment.pdf');
 40   efa.setBody(b);
 41  
 42   email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
 43  
 44   List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>{email};
 45   Messaging.SendEmailResult [] r = Messaging.sendEmail(emails);
 46   }
 47   }
 48  
 49  }