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
ForceComForceCom 

Test method Error !!!! LIST has no rows.....NEED HELP !!!!!!!!!!!

Hi , I am writing a standard controller for the contact record and below is code and test method....

 

public class ContactController {
public  Contact contact {get; set;}
public string applicationId;
public Student_Information__c studentinfo{get;set;}
    public ContactController(ApexPages.StandardController controller)
    {
        contact = new contact();
        contact.LastName = userInfo.getLastName();
        contact.FirstName = userInfo.getFirstName();
 //       String ContactId = userInfo.getContactId();

// How do I test this part from here....
        User userInfo1 = [Select ContactId, Id from User where Id =: userInfo.getUserId()];
        contact = [Select Id,firstName,lastName,Anticipated_Term_Start_Date__c,Email,Program_of_Interest__c,HomePhone,MobilePhone,Birthdate,
        Contact_Status__c,Gender__c,OtherPhone,LeadSource,MailingStreet,MailingCity,MailingCountry,MailingPostalCode,MailingState,
        OtherStreet,OtherCity,OtherCountry, OtherPostalCode,OtherState,What_are_you_applying_to__c from Contact where Id =: userInfo1.ContactId];
        
        Enrollment_Opportunity__c App = [Select id from Enrollment_Opportunity__c where Applicant__c =: Contact.Id limit 1];
        this.applicationId = App.id;
    }
     
    

  /*  public ContactController()
    {
    Id id = ApexPages.currentPage().getParameters().get('id');
    contact = (id == null) ? new Contact() :
    [SELECT id,name,phone FROM Contact WHERE id = :id];
    }*/
    
    public string getapplicationId ()
    {
        return this.applicationId;
    }    
    
    public PageReference Back()
    {
    
         upsert(contact);
 
         PageReference P = new PageReference('/apex/personalinfo?Id='+Contact.Id);
         p.setRedirect(true);
      return p;
      
   }
   
    
    public PageReference SaveNext()
    {
    
     //try
    // {
         upsert(contact);
  //       contact.LastName = userInfo.getLastName();
  //      contact.FirstName = userInfo.getFirstName();
  //       User userInfo1 = [Select ContactId, Id from User where Id =: userInfo.getUserId()];
  //      contact = [Select Id,firstName,lastName,Anticipated_Term_Start_Date__c,Email,Program_of_Interest__c,HomePhone,MobilePhone,Birthdate,
  //      Contact_Status__c,Gender__c,OtherPhone,LeadSource,MailingStreet,MailingCity,MailingCountry,MailingPostalCode,MailingState,
   //     OtherStreet,OtherCity,OtherCountry, OtherPostalCode,OtherState,What_are_you_applying_to__c from Contact where Id =: userInfo1.ContactId];
         PageReference P = new PageReference('/apex/campacademy?Id='+Contact.Id);
         p.setRedirect(true);
    // }
    // catch(System.DMLException e)
    // {
    //     ApexPages.addMessages(e);
    //  
      //}    
      
      return p;
      
   }
   public PageReference Next()
    {
    
     //try
    // {
         update(contact);
    //     User userInfo1 = [Select ContactId, Id from User where Id =: userInfo.getUserId()];
   //     contact = [Select Id,firstName,lastName,Anticipated_Term_Start_Date__c,Email,Program_of_Interest__c,HomePhone,MobilePhone,Birthdate,
   //     Contact_Status__c,Gender__c,OtherPhone,LeadSource,MailingStreet,MailingCity,MailingCountry,MailingPostalCode,MailingState,
  //     OtherStreet,OtherCity,OtherCountry, OtherPostalCode,OtherState,What_are_you_applying_to__c from Contact where Id =: userInfo1.ContactId];
         if(contact.What_are_you_applying_to__c=='Interlochen Summer Arts Camp'){
         PageReference p = new PageReference('/apex/NewCampApp?Id='+contact.id);
         p.setRedirect(true);
         return p;
         }
         else{        
         PageReference p = new PageReference('/apex/NewApplication?Id='+contact.id);
         p.setRedirect(true);
         return p;
      }
    }  

 /*  
    public PageReference Exit()
    {
    
     //try
    // {
         upsert(contact);
     
         PageReference P = new PageReference('/apex/NewCampApp?Id='+Contact.Id);
         p.setRedirect(true);
    // }
    // catch(System.DMLException e)
    // {
    //     ApexPages.addMessages(e);
    //  
      //}    
      
      return p;
      
   }
  */
     public PageReference SaveExit()
    {
    
     //try
    // {
         upsert(contact);
         PageReference P = new PageReference('/apex/customerportal');
    // }
    // catch(System.DMLException e)
    // {
    //     ApexPages.addMessages(e);
    //  
      //}    
      
      return p;
      
   }
   public PageReference submit()
    {
    
     //try
    // {
         update(contact);
         studentinfo=[Select Id from Student_Information__c where Contact__c =: Contact.Id];
         PageReference r = new PageReference('https://c.cs0.visual.force.com/apex/personalinfo1?Id='+Studentinfo.Id);
    // }
    // catch(System.DMLException e)
    // {
    //     ApexPages.addMessages(e);
    //  
      //}    
      
      return r;
      
   }
   public PageReference Camp()
    {
    
     
         update(contact);
         PageReference r = new PageReference('https://c.cs0.visual.force.com/apex/NewCampApp?Id='+contact.id);
         r.setRedirect(true);
      return r;
      
   }
   public PageReference Academy()
    {
    
         update(contact);
         PageReference r = new PageReference('https://c.cs0.visual.force.com/apex/NewApplication?Id='+contact.Id);
         r.setRedirect(true);
      
      return r;
      
   }

 

 

 

and the test method for this...is

 

@isTest
private class TestContactController {

    static testMethod void testmyController() {
        // TO DO: implement unit test
    /*    
        Map<String,ID> profiles = new Map<String,ID>();
          List<Profile> ps = [select id, name from Profile where name =
             'Standard User1' or name = 'System Administrator'];
    
          for(Profile p : ps){
             profiles.put(p.name, p.id);
          }
        */
        
        Profile p = [select id,name from profile where name='Standard User1'];
             User u = new User(alias = 'standt', email='standarduser1@testorg.com',
                emailencodingkey='UTF-8', lastname='Test1', languagelocalekey='en_US',
                localesidkey='en_US', profileid = p.Id,
                timezonesidkey='America/Los_Angeles', username='standarduser1@testorg.com');
        insert u ;
        
        contact C =New Contact (firstName=userinfo.getFirstName(),lastName=userinfo.getlastname(),id=userinfo.getUserId());
        insert C;
        
        
        Enrollment_Opportunity__c en = New Enrollment_Opportunity__c(Applicant__c =C.Id);
        insert en;
        ApexPages.currentPage().getParameters().put('id',en.Id);
        
        Enrollment_Opportunity__c en1=New Enrollment_Opportunity__c(Applicant__c=C.Id,RecordTypeId='012T00000004cfY');
        insert en1;
        ApexPages.currentPage().getParameters().put('id',en1.Id);
       
        Enrollment_Opportunity__c en2=New Enrollment_Opportunity__c(Applicant__c=C.Id,RecordTypeId='012T00000004cfd');
        insert en2;
        ApexPages.currentPage().getParameters().put('id',en2.Id);
        
       //  ApexPages.StandardSetController ssc = new ApexPages.StandardSetController(accountList);
       // ApexPages.StandardController co=new ApexPages.StandardController(C);
        
        ContactController co = new ContactController(new ApexPages.StandardController(C));
               
        co.getapplicationId();
        co.back();
        co.SaveNext();
        co.Next();
        co.SaveExit();
        co.Submit();
        co.Camp();
        co.Academy();
        
    }
}

 

I am not able to test the user record.......I am receiving an error as LIST HAS NO ROWS FOR ASSIGNMENT TO SOBJECT...at the profile query....

 

what to do...where am I going wrong...

 

Best Answer chosen by Admin (Salesforce Developers) 
sravusravu

Ok in the test class you can create a customer portal user and run the test class as that user and try.

1.Create an Account

2. Create a contact and associate with this account

3.Then create a user and give the conatctId and assign customer portal profile Id to this user

4.User system.runAs(user); method in the test class

All Answers

uptime_andrewuptime_andrew

Does the profile "Standard User1" actually exit?  Should that be "Standard User"?

 

 

        Profile p = [select id,name from profile where name='Standard User1'];

 

 

ForceComForceCom

Hi ,

 

No it does not exist, I have used Standard User , its a typo.....but I have the same error...

 

Is the syntax for the controller extension that I used here in the test method ...correct ?

 

 

sravusravu

Try this and see:

 

@isTest
private class TestContactController {
    static testMethod void testmyController() {
               
        Account acc = new Account();
        acc.Name ='myName';
        insert acc;
        
        Contact con =new Contact();
        con.FirstName='FirstTestName';
        con.LastName ='LastTestName';
        con.AccountId= acc.Id;
        con.Anticipated_Term_Start_Date__c
        con.Email='test@email.com';
        con.Program_of_Interest__c=
        con.HomePhone=
        con.MobilePhone=
        con.Birthdate=
        con.Contact_Status__c=
        con.Gender__c=
        con.OtherPhone=
        con.LeadSource=
        con.MailingStreet=
        con.MailingCity=
        con.MailingCountry=
        con.MailingPostalCode=
        con.MailingState=
        con.OtherStreet=
        con.OtherCity=
        con.OtherCountry=
        con.OtherPostalCode=
        con.OtherState=
        con.What_are_you_applying_to__c=
        insert con;
        
        ApexPages.StandardController controller = new ApexPages.StandardController(con);
        ContactController cc = new ContactController(controller);        
        
        User user = new User();
        user.Username ='testemail@test.com';
        user.LastName = 'LastTestName';
        user.Email = 'testemail@test.com';
        user.alias = 'testAl';
        user.TimeZoneSidKey = 'America/New_York';
        user.LocaleSidKey = 'en_US';
        user.EmailEncodingKey = 'ISO-8859-1';
        user.ProfileId = [select id from Profile where Name='System Administrator'].Id;
        user.LanguageLocaleKey = 'en_US';
        user.ContactId=con.Id;
        insert user;
        
        Enrollment__Opportunity__c opp = new Enrollment_Opportunity__c();
        //Insert the required fields
        opp.Applicant__c = con.Id;
        insert opp;
        
        User tUser = [select ContactId, Id from User where Id = :user.Id];
        
        Contact tContact = [Select Id,firstName,lastName,Anticipated_Term_Start_Date__c,Email,Program_of_Interest__c,HomePhone,MobilePhone,Birthdate,
        Contact_Status__c,Gender__c,OtherPhone,LeadSource,MailingStreet,MailingCity,MailingCountry,MailingPostalCode,MailingState,
        OtherStreet,OtherCity,OtherCountry, OtherPostalCode,OtherState,What_are_you_applying_to__c from Contact where Id =:user.ContactId];
                
        Enrollment_Opportunity__c app = [select id from Enrollment_Opportunity__c where Applicant__c=:con.Id];

//From here you can test the methods and PageReference methods you can call them as void

 

 

Please let me know if you face any difficulty.

 

ForceComForceCom

Hi ,

Thank you so much for your help....but I am facing the same error at the same location...I am not able to cover this part ..

 

User userInfo1 = [Select ContactId, Id from User where Id =: userInfo.getUserId()];

        contact = [Select Id,firstName,lastName,Anticipated_Term_Start_Date__c,Email,Program_of_Interest__c,HomePhone,MobilePhone,Birthdate,
 Contact_Status__c,Gender__c,OtherPhone,LeadSource,MailingStreet,MailingCity,MailingCountry,MailingPostalCode,MailingState,   OtherStreet,OtherCity,OtherCountry, OtherPostalCode,OtherState,What_are_you_applying_to__c from Contact where Id=userInfo1.ContactId];

 

It gives an error as List has No rows for assignment to SObject.....here..!!!


StephenBStephenB

Hi, you're not linking the Contact to the User - so when you try and select a Contact where Id = userinfo1.CotnactId it's going to fail.

 

Best practice here would be to use system.runAs() - in your test class you would

- create a Contact first

- create a User with ContactId = <contact ID from above>

- system.runAs(u)

- then execute your test cases

 

Also it's not clear to me why you even need to worry about a User in your test code - it dioesn't appear to be used in any of your controller logic? Can't you just create a Contact record and use that to test your logic?

 

S

ForceComForceCom

I use the user record in the logic too.....that where i query for the contact record , and use that contact record in subsequent step...

 

I used ...system.runas()...still i face the same error....It shows the contactId in the test record , but in the debug log it shows the contactId as null in the original class.....when run test....

sravusravu

The problem must be with the SOQL queries in the class.

Try to debug each query and see if you are fetching the results.

 

  User userInfo1 = [Select ContactId, Id from User where Id =: userInfo.getUserId()];
        contact = [Select Id,firstName,lastName,Anticipated_Term_Start_Date_

_c,Email,Program_of_Interest__c,HomePhone,MobilePhone,Birthdate,
        Contact_Status__c,Gender__c,OtherPhone,LeadSource,MailingStreet,MailingCity,MailingCountry,MailingPostalCode,MailingState,
        OtherStreet,OtherCity,OtherCountry, OtherPostalCode,OtherState,What_are_you_applying_to__c from Contact where Id =: userInfo1.ContactId];//Check whether this is retrieving any rows

//May be if you are the system adminstrator your contactId will be null. So this might be causing the error

//Check this once

ForceComForceCom

Yeah , exactly that is the error....

ForceComForceCom

How can I rectify this...now...?

 

sravusravu

So this is what happening. when you trying to get the contactId of the current user and testing the code it is failing as list has no rows to retrieve.

Can you tell me what exactly you are trying to do in the controller?

Your are creating a new contact and assigning userInfo.getFirstName() and all. It is little bit confusing. Could you explain exactly what you are doing in the code?

ForceComForceCom

Hi

 

So, What I am trying to do is...

 

I use a customer portal and I have a contact standard object and an application custom object....so, when a user logs into the portal , he should see his first name , last name on the page , which he edits....so in that sense, what I have done , captured the contact record from the user ...

sravusravu

In that case you need to select the user that has teh customer portal profile. So that you will not have any null value for the contactId in user.

Profile p = [select Id from profile where Name = <customer portal profile name'];

User user = [select ContactId from User where profileId=:p];

ForceComForceCom

Hi

Yeah I can do that, but I need to get the exact contact record Id each time and pass that record Id...

 

sravusravu

Ok you can get the current logged in user into the portal in the following way:

 

Profile p = [select Id from profile where Name = <customer portal profile name>];

User user = [select ContactId from User where profileId=:p and id = :userInfo.getUserId()];

// This will given you the contactId for the current logged in user

Hope this resolves your issue.

ForceComForceCom

I have tried ...that many times...but no luck so far...!!!

ForceComForceCom

i think ....the reason might be....

 

Since the customer portal profile name is portal user....and it searches for the contactId with portal user profile but for the current user....the...current user is the system administrator....so it is still not fetching me the contactId....

 

 

sravusravu

Ok in the test class you can create a customer portal user and run the test class as that user and try.

1.Create an Account

2. Create a contact and associate with this account

3.Then create a user and give the conatctId and assign customer portal profile Id to this user

4.User system.runAs(user); method in the test class

This was selected as the best answer
ForceComForceCom

Thank you so much ...it worked like a charm now...