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
jaanvivekjaanvivek 

Regarding Test Class For following Apex class

Hello EveryOne,

 

I'm trying to write a Test class for the below Apex class. While runnig the test class i'm getting error like

"System.QueryException: List has no rows for assignment to SObject

 

Class.sendemail.sendEmailOnContacts: line 13, column 1 Class.sendemail.TestshowContacts: line 54, column 1"

 

 

Please find the below mentioned code snippet-

 

public class sendemail
{
String STR;
public sendemail()
{
STR=apexpages.currentpage().getparameters().get('id');
system.debug('Debug Statements=====>'+STR);
}
public pagereference sendEmailOnContacts(){
try
{

contact conobj=[select id,email from contact where id=:STR];
system.debug('Email Data=========>'+conobj.email);



Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String VarEmailSetting=conobj.email;
String[] toAddresses = new String[] {VarEmailSetting};

System.debug('<==============>'+toAddresses);

mail.setToAddresses(toAddresses);
mail.setSubject('Contact Information');
mail.setPlainTextBody('Hi You Are Added To Our System As Contacts');
mail.setReplyTo('jaan.vivek746@gmail.com');
mail.setSenderDisplayName('HR Management');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });


pagereference pagref=new pagereference('/'+conobj.id);
return pagref;
}
catch(System.EmailException ex)
{
system.debug('no emailid========>');
return null;
}

}
//**********************Test Class************************
static testMethod void TestshowContacts()
{
sendemail testObj=new sendemail ();
Contact con = new Contact();
con.FirstName = 'abc';
con.LastName = 'hi';
con.Email = 'abc.hi@gmail.com';
insert con;
Messaging.SingleEmailMessage testmail = new Messaging.SingleEmailMessage();
String testVarEmailSetting=con.Email;
String[] testtoAddresses = new String[] {testVarEmailSetting};
testmail.setToAddresses(testtoAddresses);
testObj.sendEmailOnContacts();
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { testmail });
 }
}

 

 

I don't have much hands on on sfdc but i'm eager to learn it.

 

It would be great help if you suggest me in this case.

 

 

Thanks for your valuable help.

 Your suggestions are always welcome.

 

Vivek


Best Answer chosen by Admin (Salesforce Developers) 
metaforcemetaforce

your test method should look like this: 

-------------------------------------------

static testMethod void TestshowContacts()
{
sendemail testObj = new sendemail ();
Contact con = new Contact();
con.FirstName = 'abc';
con.LastName = 'hi';
con.Email = 'abc.hi@gmail.com';
insert con;

// insert the line below to set the STR variable to contactId that you get from the posted parameters in the real world scenario

testObj.STR = con.Id;
testObj.sendEmailOnContacts();
}

 

Remember that test methods are not just for code coverage, instead they are there to make sure that your method returns the expected output. So do include assert statements also in your test method.

All Answers

Navatar_DbSupNavatar_DbSup

Hi,

Try the below modified code snippet:

 

public class sendemail

{

    String STR;

    public sendemail()

    {

        STR=apexpages.currentpage().getparameters().get('id');

        system.debug('Debug Statements=====>'+STR);

    }

    public pagereference sendEmailOnContacts()

    {

        try

        {

 

            contact conobj=[select id,email from contact where id=:STR];

            system.debug('Email Data=========>'+conobj.email);

 

 

 

            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

            String VarEmailSetting=conobj.email;

            String[] toAddresses = new String[] {VarEmailSetting};

 

            System.debug('<==============>'+toAddresses);

 

            mail.setToAddresses(toAddresses);

            mail.setSubject('Contact Information');

            mail.setPlainTextBody('Hi You Are Added To Our System As Contacts');

            mail.setReplyTo('jaan.vivek746@gmail.com');

            mail.setSenderDisplayName('HR Management');

            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

 

 

            pagereference pagref=new pagereference('/'+conobj.id);

            return pagref;

        }

        catch(System.EmailException ex)

        {

            system.debug('no emailid========>');

            return null;

        }

 

    }

   

    //**********************Test Class************************

static testMethod void TestshowContacts()

{

Contact con = new Contact();

con.FirstName = 'abc';

con.LastName = 'hi';

con.Email = 'abc.hi@gmail.com';

insert con;

ApexPages.CurrentPage().getParameters().put('id', con.Id);  // add this line

sendemail ss1=new sendemail();

ss1.sendEmailOnContacts();

 

Contact con1 = new Contact();

con1.FirstName = 'abc';

con1.LastName = 'hi';

 

insert con1;

ApexPages.CurrentPage().getParameters().put('id', con1.Id);

sendemail ss=new sendemail();

ss.sendEmailOnContacts();

 }

   

}

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved. 

Starz26Starz26

You did not instantiate a visualforce pagereference and thus there is no IT to get from the parameters, it is returning null and your query returns no records.

 

If there is a possibility of returning no results, your query should be returning its values to a list of contacts and not a single object.

 

Here is some good infor on test methods. Skip down to the part about testing visualforce controllers:

 

http://wiki.developerforce.com/page/An_Introduction_to_Apex_Code_Test_Methods

metaforcemetaforce

your test method should look like this: 

-------------------------------------------

static testMethod void TestshowContacts()
{
sendemail testObj = new sendemail ();
Contact con = new Contact();
con.FirstName = 'abc';
con.LastName = 'hi';
con.Email = 'abc.hi@gmail.com';
insert con;

// insert the line below to set the STR variable to contactId that you get from the posted parameters in the real world scenario

testObj.STR = con.Id;
testObj.sendEmailOnContacts();
}

 

Remember that test methods are not just for code coverage, instead they are there to make sure that your method returns the expected output. So do include assert statements also in your test method.

This was selected as the best answer
Starz26Starz26

metaforce wrote:

your test method should look like this: 

-------------------------------------------

static testMethod void TestshowContacts()
{
sendemail testObj = new sendemail ();
Contact con = new Contact();
con.FirstName = 'abc';
con.LastName = 'hi';
con.Email = 'abc.hi@gmail.com';
insert con;

// insert the line below to set the STR variable to contactId that you get from the posted parameters in the real world scenario

testObj.STR = con.Id;
testObj.sendEmailOnContacts();
}

 

Remember that test methods are not just for code coverage, instead they are there to make sure that your method returns the expected output. So do include assert statements also in your test method.


 

Which is exactly why you DO NOT want to set the value of STR using the test method. The controller is getting the value from an apex page. In order to test it is working properly you need to instantiate a pagereference and put the ID parameter there prior to instantiating the controller.....

 

metaforcemetaforce

agree to starz26 : "you need to instantiate a pagereference and put the ID parameter there prior to instantiating the controller"

jaanvivekjaanvivek

Thnx You all for your valuable solutions.

 

I tried 

 

static testMethod void TestshowContacts()
{
sendemail testObj = new sendemail ();


Contact con = new Contact();
con.FirstName = 'abc';
con.LastName = 'hi';
con.Email = 'abc.hi@gmail.com';
insert con;
// insert the line below to set the STR variable to contactId that you get from the posted parameters in the real world scenario

testObj.STR = con.Id;
testObj.sendEmailOnContacts();
}

 

 

But still it's 89% it's missing to include  catch block also.

jaanvivekjaanvivek
Thnx Starz26

I tried to instantiate a pagereference and put the ID parameter there like-

pagereference testpagref=new pagereference(con.id);

but it was not covering the code.

Could you plz brief me how can i do in my case.

Thanks for your all help.
Starz26Starz26

 

1. What is the name of the page that is using this controller

2. Did you actually click the link I gave you above and read the section on the Test methods for visualforce controllers? The begingin of the example given there is exactly what you need to do..

3. I do not see the code where you attempted to do this so I am assuming you got and attempt to dereference error as you may not have set the test.setCurrentPage etc.....

jaanvivekjaanvivek

I'm using this controller in sendemail VF page

<apex:page controller="sendemail" action="{!sendEmailOnContacts}" >

</apex:page>


I tried like this-

static testMethod void TestshowContacts()
{
sendemail testObj = new sendemail ();
Contact con = new Contact();
con.FirstName = 'abc';
con.LastName = 'hi';
con.Email = 'abc.hi@gmail.com';
insert con;
// insert the line below to set the STR variable to contactId that you get from the posted parameters in the real world scenario

pagereference testpagref=new pagereference(con.id);
//testObj.STR = con.Id;
testObj.sendEmailOnContacts();

}

I went through the link, still trying to find out the help from that.
Thanks for your help.

bharath kuamarbharath kuamar

public class DonorDetailsController
{
        public List<CommitmentDetails> commitmentDetailsList {get;set;}
        public List<PaymentDetails> paymentDetailsList {get;set;}
        public Preference__c preObj {get;set;}
        public String contactId {get;set;}
        public String preferenceId {get;set;}
        public DonorDetailsController()
        {
            User oUser = [Select Id, ContactId From User Where Id=:UserInfo.getUserId()];
            contactId = oUser.contactId;
            preObj = new Preference__c();                
            getAllCommitmentDetails();
            getAllPaymentDetails();
        }   
        public class CommitmentDetails
        {
            public String childName {get;Set;}
            public String projectName {get;set;}
            public String commitmentType {get;set;}
            public String commitmentStartDate {get;set;}
            public String commitmentEndDate {get;set;}
            public String perferenceId {get;set;}
            public String childId {get;set;}
        }

        public class PaymentDetails
        {
            public Double amount {get;set;}
            public Double opportunityAmount {get;set;}
            public String paymentMode {get;set;}
            public String paymentFrequency {get;set;}
            public Date paymentStartDate {get;set;}
            public Date paymentEndDate {get;set;}
            public String paymentStatus{get;set;}
        }
        public void getAllCommitmentDetails()
        {
            commitmentDetailsList = new List<CommitmentDetails>();
            for (Commitment__c oCommitment : [Select Id, Child__c, Child__r.Name, Start_Date__c, Project__c,
                                                                    Project__r.Name, Commitment_Type__c, End_Date__c,
                                                                    Preference__c, Status__c From Commitment__c Where Contact__c=:contactId])
                                                                     
           //System.debug(oCommitment);
            {
                CommitmentDetails oCommitmentDetails = new CommitmentDetails();
                oCommitmentDetails.childName = oCommitment.Child__r.Name;
                oCommitmentDetails.projectName = oCommitment.Project__r.Name;
                oCommitmentDetails.commitmentType = oCommitment.Commitment_Type__c;
                oCommitmentDetails.commitmentStartDate = oCommitment.Start_Date__c != null ? oCommitment.Start_Date__c.format() : '';
                oCommitmentDetails.commitmentEndDate = oCommitment.End_Date__c != null ? oCommitment.End_Date__c.format() : '';
                oCommitmentDetails.perferenceId = oCommitment.Preference__c;
                oCommitmentDetails.childId = oCommitment.Child__c;
                commitmentDetailsList.add(oCommitmentDetails);
                
            }  
           
            
        }
        public void getAllPaymentDetails()
       {
            paymentDetailsList = new List<PaymentDetails>();
            String opportunityId = [Select OpportunityId From OpportunityContactRole Where ContactId=:contactId limit 1].OpportunityId;
            for (Payment_Schedule__c obj : [Select Amount__c, Payment_End_Date__c, Opportunity__r.Amount,
                                                                      Payment_Frequency__c, Payment_Mode__c, Payment_Start_Date__c
                                                             From Payment_Schedule__c Where Opportunity__c=:opportunityId])
            {
                PaymentDetails oPaymentDetails = new PaymentDetails();
                oPaymentDetails.amount = obj.Amount__c;
                oPaymentDetails.opportunityAmount = obj.Opportunity__r.Amount;
                oPaymentDetails.paymentMode = obj.Payment_Mode__c;
                oPaymentDetails.paymentFrequency = obj.Payment_Frequency__c;
                oPaymentDetails.paymentStartDate = obj.Payment_Start_Date__c;
                oPaymentDetails.paymentEndDate = obj.Payment_End_Date__c;   
                paymentDetailsList.add(oPaymentDetails);
            }
       }
       public void loadPreference()
      {
          preObj = [Select Id, Age_From__c, Age_To__c, Sex__c,
                                    Continent__c, Country__c, Language__c, Religion__c
                                    From Preference__c Where Id=:preferenceId];
          System.debug( preObj  + ' == ' );                                     

      }

 

please help me with the following class