+ Start a Discussion
shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com 

Test Class for insert method.

Hi,

 I have a class that enters values(from a lookup) in AccountTeamMember object from a custom visualForce page.There are 3 main parametres that are supposed to be entered

1.AccountName(Look up)

2.UserName(Look up)

3.TeamMemberRole(dropdown)

The method is given below:

 public void save(){
   try
    {      
       if (accTeamMem == null)  
                      {      
                        accTeamMem = new AccountTeamMember(); 
                       } 
      String accountID =  ApexPages.currentPage().getParameters().get('searchAccount');
      String UserID  =  ApexPages.currentPage().getParameters().get('searchName');  
      String teamMemberRole = ApexPages.currentPage().getParameters().get('searchRole');     
      system.debug('accountid ='+accountID );
     system.debug('accountid ='+UserID );
     // system.debug('accountid ='+teamMemberRole );      
      insert accTeamMem;   
    }
     Catch (DMLException e) { 
       ApexPages.addMessages(e);      
        }   
          
        //return null;
     LoadData();
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Your entry has been added')); 

        }        
Custom controller used:  TeamMemberAssignmentController 

I wanna write a test class for this method, so far this is what i've done:

 

 

@isTest
private class TestTeamMemberAssignmentController    {

static testMethod void runTest() {
User u = [Select id,name from User where id = :UserInfo.getUserID()];
        ApexPages.currentPage().getParameters().put('searc​hAccount','a2');
        ApexPages.currentPage().getParameters().put('searc​hName','u.id');
        ApexPages.currentPage().getParameters().put('searc​hRole','Account Manager');
        
        TeamMemberAssignmentController c = new TeamMemberAssignmentController();
        
        c.save(); 
}
}

This is showing "insert failed" error u.id and a2 are not getting inserted.Please help me,this is my first test class!!!!

Thanks

ashish raiashish rai

Hello,

       Well you have forget to mention the reqired field value inside you custom objcet before you are inserting.

 

public void save()

 try   

{           

 if (accTeamMem == null)                       

{                              accTeamMem = new AccountTeamMember();                        }    

  String accountID =  ApexPages.currentPage().getParameters().get('searchAccount');     

String UserID  =  ApexPages.currentPage().getParameters().get('searchName');       

String teamMemberRole = ApexPages.currentPage().getParameters().get('searchRole');           s

ystem.debug('accountid ='+accountID );     system.debug('accountid ='+UserID );     // system.debug('accountid ='+teamMemberRole );  

accTeamMem.name='xyz';        

accTeamMem.accountID=accountID;  

accTeamMem.UserID=UserID;  

accTeamMem.teamMemberRole=teamMemberRole;  

insert accTeamMem;       }     

Catch (DMLException e)  {        ApexPages.addMessages(e);              }                     //return null;     LoadData();ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Your entry has been added')); }      

There is no any issue with the test method. You have to simply made few changes inside your save() method which i have mentioned above.

 

Think this will help you.

 

 

shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com

I've done exactly what you told me, but still I am getting this error

 

System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [AccountId, UserId]: [AccountId, UserId]

 

Here I'd like to mention that AccountId and UserId are required feilds to add any entry to accountTeamMember object.

shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com

Hi,

   I think i've got the problem, the main problem is that in test class I am using this line

 

 

ApexPages.currentPage().getParameters().pu​t('searc​hAccount','a2');
        ApexPages.currentPage().getParameters().pu​t('searc​hName','u.id');

 

 

all parametres are getting passed in test class but they are not gettin in save method , because i've used ApexPages.currentPage().  and in this test class this method returns null

 

now I dont know how to rectify this thing please help.

 

I've written a seperate class for testing, will it help if i club the test class with the main one??????

Thanks

Rahul SharmaRahul Sharma

try this:

 

@isTest
private class TestTeamMemberAssignmentController    {
static testMethod void runTest() {
Account a2 = new Account(Name = 'Test Account - 001');
User u = [Select id,name from User where id = :UserInfo.getUserID()];
        ApexPages.currentPage().getParameters().put('searc​hAccount',a2);
        ApexPages.currentPage().getParameters().put('searc​hName',u.id);
        ApexPages.currentPage().getParameters().put('searc​hRole','Account Manager');
        
        TeamMemberAssignmentController c = new TeamMemberAssignmentController();
        
        c.save(); 
}
}

 I think the problem was due to you were passing the String instead of Actual Id's.

Hope it helps

shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com

Not working

I am getting this error

Error: Compile Error: Incompatible value type SOBJECT:Account for MAP<String,String> at line 51 column 49 

ine 51 is this line

ApexPages.currentPage().getParameters().put('searc​hAccount',a2);
L

Rahul SharmaRahul Sharma
ApexPages.currentPage().getParameters().put('searc​hAccount',a2.Id);

 Missed the .Id, this must work.

ashish raiashish rai

Hello,

    Well you have passed invalid user and account id inside your test methods.Use this

 

Account ac=new account(name='hello');

insert ac;      

ApexPages.currentPage().getParameters().pu​t('searc​hName',u.id);

ApexPages.currentPage().getParameters().pu​t('searc​hAccount',ac.id);

 

 

Think this will help you.

shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com

Hi Rahul,

            Thanks a lot for your help, but even after doing what u asked me to do, I am still getting the same error.It says

Insert Failed required feilds missing i.e accountId AND uSERiD

 

shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com

Hi Ashish,

             I've tried your solution and I am getting the same error that is

Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [AccountId, UserId]: [AccountId, UserId]

Rahul SharmaRahul Sharma

That must have work,

Anyways, put debug statements in the save method checking if the values are passed or not.

It would help to identify the problem, also check line number where you face exception.

PkSharmaPkSharma

Hi,

 

Please copy the searchAccount,searchName string from test method  and replace it into class and save that class.I try it and its working fine . please test it.

thanks



ashish raiashish rai

Hello,

    Well try the PK solution its really working but still confused what makes difference between this and which i have sujected.

shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com

Hi All,

         As suggested , I have used System.debug the code is given below:

static testMethod void runTest() {
User u = [Select id,name from User where id = :UserInfo.getUserID()];
system.debug('user id. in test class...........................');
system.debug(u.id);
Account acc=[select id from Account limit 1];

 

system.debug('account id..in test class...........................');
system.debug(acc.id);
      ApexPages.currentPage().getParameters().put('searc​hAccount',acc.id);
      ApexPages.currentPage().getParameters().put('searc​hName',u.id);
       ApexPages.currentPage().getParameters().put('searc​hRole','Account Manager');
        
        TeamMemberAssignmentController c = new TeamMemberAssignmentController();
        
     c.save(); 
Till system.debug(acc.id) its working fine, but these values are not getting passed into the save method of my custom controller..

shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com

Hi pk,

        Thanks a lot for investing your time in helping me, I have'nt completely understood your solution, can you please elaborate a bit more. Please help me it's really urgent.

Thanks

Rahul SharmaRahul Sharma

I meant to put the debugs in your controller, so as to ensure if the value of the page parameters is passed (from Test

class to controller)  are not.

 

Example:

Controller-

public void save(){
 try
 {      
  if (accTeamMem == null)  
  {      
   accTeamMem = new AccountTeamMember(); 
  } 
  String accountID =  ApexPages.currentPage().getParameters().get('searchAccount');
  String UserID  =  ApexPages.currentPage().getParameters().get('searchName');  
  String teamMemberRole = ApexPages.currentPage().getParameters().get('searchRole');     
  system.debug('==accountID in controller=='+accountID); system.debug('==UserID in controller=='+UserID); system.debug('==teamMemberRole in controller=='+teamMemberRole);      
  insert accTeamMem;   
 }
 Catch (DMLException e) { 
   ApexPages.addMessages(e);  
   system.debug('====Check this exception too===='+e);    
 }   
          
        //return null;
 LoadData();
 ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Your entry has been added')); 
} 

 There might be some validation/ criteria required to create a Team Member record. try it, it would help in debugging.

 

Test class-

@isTest
private class TestTeamMemberAssignmentController    {
static testMethod void runTest() {
Test.Start();
try{
Account a2 = new Account(Name = 'Test Account - 001');
insert a2;
User u = [Select id,name from User where id = :UserInfo.getUserID()];
        ApexPages.currentPage().getParameters().put('searc​hAccount',a2.Id);
        ApexPages.currentPage().getParameters().put('searc​hName',u.id);
        ApexPages.currentPage().getParameters().put('searc​hRole','Account Manager');
        
        TeamMemberAssignmentController c = new TeamMemberAssignmentController();
        c.save(); 
}
catch(exception e){
system.debug('====Exception in test class===='+e);
}
Test.Stop();
}
}

 Create valid data in test class, which are required for creating a Team Member.

Use same set of data which you do while testing to ensure the data is proper.

 

Hope it helps in finding the cause.

 

shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com

Hi rahul,

 I tried what you told me. Alo three system.debug statements in apex class( that you added ) are returning null.And data that is created in test class is valid, so the issue is that the data is not gettin into the class. How to rectify that? please help.

Thanks

Rahul SharmaRahul Sharma

Try this, 

@isTest
public class TestTeamMemberAssignmentController    {
pulic static testMethod void runTest() {
Test.Start();
try{
TeamMemberAssignmentController c = new TeamMemberAssignmentController();
Account a2 = new Account(Name = 'Test Account - 001');
insert a2;
User u = [Select id,name from User where id = :UserInfo.getUserID()];
        ApexPages.currentPage().getParameters().put('searc​hAccount',a2.Id);
        ApexPages.currentPage().getParameters().put('searc​hName',u.id);
        ApexPages.currentPage().getParameters().put('searc​hRole','Account Manager');
        c.save(); 
}
catch(exception e){
system.debug('====Exception in test class===='+e);
}
Test.Stop();
}
}

 

shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com

Hi,

 It's still the same, variables are not going in the save method of class.

Rahul SharmaRahul Sharma

Is your controller and class(methods) public,

Just ensure once that your are calling proper class.

It will be useful if you post your whole code.

shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com

Class:

 

public with sharing class TeamMemberAssignmentController {
 
  //private ApexPages.StandardController controller {get; set;}
     public List<AccountTeamMember> accs { get; set; }
      public string SelectedAccountTeamMemberId { get; set; }
       //used to get a hold of the account team member record selected for deletion
  public List<AccountTeamMember> searchResults {get;set;}
  public List<AccountTeamMember> ListDeleted {get;set;}
  public String searchText {get;set;}
  public List<cAccountTeamMember> AccountTeamMemberList {get; set;}
  // standard controller - could also just use custom controller
  public TeamMemberAssignmentController() { }
 
  // fired when the search button is clicked
  public PageReference search() {
    //String qry = 'select UserId,TeamMemberRole from AccountTeamMember where UserId IN (SELECT UserId FROM User WHERE Username="{!searchText}")';
    String qry = 'SELECT User.Name,Account.Name,TeamMemberRole,IsDeleted FROM AccountTeamMember ';
   // UserId = \''+accTeamMem.UserId+'\' OR AccountId = \''+accTeamMem.AccountId+'\'';
    qry = qry + getWhereClause();
    System.debug(qry);
    searchResults = Database.query(qry);
    return null;
  
  }
 
  // fired when the save records button is clicked
  //public PageReference save() {   
  public void save(){
   try
    {     
       if (accTeamMem == null) 
                      {     
                        accTeamMem = new AccountTeamMember();
                       }
      String accountID =  ApexPages.currentPage().getParameters().get('searchAccount');
      String UserID  =  ApexPages.currentPage().getParameters().get('searchName'); 
      String teamMemberRole = ApexPages.currentPage().getParameters().get('searchRole');
      system.debug('==accountID in controller=='+accountID);
       system.debug('==UserID in controller=='+UserID);
       system.debug('==teamMemberRole in controller=='+teamMemberRole);       
      insert accTeamMem;  
    }
     Catch (DMLException e) {
       ApexPages.addMessages(e);
       system.debug('====Check this exception too===='+e);        
        }  
         
        //return null;
     LoadData();
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Your entry has been added'));

        }       
  // takes user back to main record
  public Pagereference RTSelector()

    {

        PageReference nextPage;

            nextPage = new PageReference('/apex/MassATM');

            nextPage.setRedirect(true);     return nextPage;

    }
 public Pagereference RTSelector1()

    {

        PageReference nextPage;

            nextPage = new PageReference('/apex/TeamAssignmenPage');

            nextPage.setRedirect(true);     return nextPage;

    }

 //public PageReference update1() {
public void update1(){
 
    try {
      update  searchResults ;
System.debug(searchResults);
    } Catch (DMLException e) {
      ApexPages.addMessages(e);
       //return null;

    }
   
     LoadData();
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Your entry has been edited'));
         }

 public void delete1()
{
 integer i;
  for (i=0;i<searchResults.size();i++)
       {
          accTeamMem = searchResults.get(i);
          ListDeleted.add(accTeamMem);
           System.debug('Userid ='+accTeamMem.UserId);
            System.debug('IsDel ='+accTeamMem.IsDeleted);
               System.debug('AccounId ='+accTeamMem.AccountId);
       }
 delete ListDeleted;
}
//
 
 public AccountTeamMember accTeamMem
        {
            get
            {
                if (accTeamMem == null)
                {
                    accTeamMem = new AccountTeamMember();
                }
                return accTeamMem;
            }
            set;
        }  
       
 
  public String getWhereClause()
  {        
       String whereClause = 'IsDeleted=false';

       if (accTeamMem.UserId != null)
       {
         whereClause +='UserId = \''+accTeamMem.UserId+'\'';
       }
       if (accTeamMem.AccountId != null)
       {
         if (whereClause != '')
                        whereClause += ' and ';
         whereClause +='AccountId = \''+accTeamMem.AccountId+'\'';
       }
       if (accTeamMem.TeamMemberRole != null)
       {
         if (whereClause != '')
                        whereClause += ' and ';
         whereClause +='TeamMemberRole = \''+accTeamMem.TeamMemberRole+'\'';
       }
       if (whereClause != '')
       {
        whereClause = ' WHERE ' + whereClause;
       }
      
     return whereClause;

  }
//account TeamMember entry deletion method
 // private void LoadData() {
//System.debug('in loaddata ------2');
       //cs = [Select User.name, Account.name,TeamMemberRole from AccountTeamMember limit 20];
 //}
 private void LoadData() {
       searchResults= [Select User.name, Account.name,TeamMemberRole from AccountTeamMember limit 20];
   }

 

public void DeleteAccount()
   {
      // if for any reason we are missing the reference
      if (SelectedAccountTeamMemberId== null) {

         return;
      }

      // find the account record within the collection
      AccountTeamMember tobeDeleted = null;
      for(AccountTeamMember a : searchResults)
       if (a.Id == SelectedAccountTeamMemberId) {
          tobeDeleted = a;
          break;
       }

      //if account record found delete it
      if (tobeDeleted != null) {
       Delete tobeDeleted;
      }

      //refresh the data
      LoadData();
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Your has been deleted'));
   }   


/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////MASS DELETE FUNCTION/////////////////////////////////////
 public List<cAccountTeamMember> getAccountTeamMembers() { 

         if(AccountTeamMemberList == null) { 

             AccountTeamMemberList = new List<cAccountTeamMember>(); 

             for(AccountTeamMember c : [select User.Name,Account.Name,AccountTeamMember.TeamMemberRole  from AccountTeamMember limit 10]) { 

                 // As each contact is processed we create a new cContact object and add it to the contactList 
              AccountTeamMemberList.add(new cAccountTeamMember(c)); 

             } 

         } 

         return AccountTeamMemberList; 

     } 

public void processSelected() { 

   

                 //We create a new list of Contacts that we be populated only with Contacts if they are selected 

         List<AccountTeamMember> selectedAccountTeamMembers = new List<AccountTeamMember>(); 

   

         //We will cycle through our list of cContacts and will check to see if the selected property is set to true, if it is we add the Contact to the selectedContacts list 

         for(cAccountTeamMember cCon : getAccountTeamMembers()) { 

             if(cCon.selected == true) { 

                 selectedAccountTeamMembers.add(cCon.con); 

             } 

         } 

   

         // Now we have our list of selected contacts and can perform any type of logic we want, sending emails, updating a field on the Contact, etc 

         System.debug('These are the selected Contacts...'); 

         for(AccountTeamMember con : selectedAccountTeamMembers) { 

             system.debug(con); 
delete selectedAccountTeamMembers;
 

         } 

        LoadData();
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Your entries have been deleted'));


     } 
public class cAccountTeamMember { 

         public AccountTeamMember con {get; set;} 

         public Boolean selected {get; set;} 

   

         //This is the contructor method. When we create a new cContact object we pass a Contact that is set to the con property. We also set the selected value to false 

         public cAccountTeamMember(AccountTeamMember c) { 

             con = c; 

            selected = false; 

         } 

    } 

 

  }

Test class is the same as suggested by you!!!

Rahul SharmaRahul Sharma

move the getparameters part to constructor and try with removing AccTeamMember != null Check from save function.

public with sharing class TeamMemberAssignmentController {
  public String accountID = '';
  public String teamMemberRole = '';
  public String UserID = '';
  public TeamMemberAssignmentController() {
    accountID = ApexPages.currentPage().getParameters().get('searchAccount');
    UserID = ApexPages.currentPage().getParameters().get('searchName');  
    teamMemberRole = ApexPages.currentPage().getParameters().get('searchRole');
  }   
  public void save(){
   try
    {    
       accTeamMem = new AccountTeamMember();
       accTeamMem.UserId = UserId; accTeamMem.accountID = accountID; accTeamMem.teamMemberRole = teamMemberRole;
       system.debug('==accountID in controller=='+accountID); 
       system.debug('==UserID in controller=='+UserID); 
       system.debug('==teamMemberRole in controller=='+teamMemberRole);        
      insert accTeamMem; 

 I also noticed you didn't assigned the values of fields of TeamMember object while inserting in save function.

Replace field names highlighted in blue with actual field names.

shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com

Hi rahul,

       Thanks a lot for your timea and effort, now the feilds are getting loaded into the class. There is just one last thing that i want to ask you,  The last point that you mentioned (changing the blue coloured feilds) .Can you please elaborate it .

AccountTeamMember has feilds

1.UserId

2.AccountId

3.TeamMemberRole

The names(Id's) of  these feilds on vf page is:

1.searchAccount

2.searchName

3.searchRole

And input values on vf page are:

1."{!accTeamMem.AccountId}"

2."{!accTeamMem.UserId}"

3."{!accTeamMem.TeamMemberRole}"

         Now what am i supposed to edit?

Thanks again

bob_buzzardbob_buzzard

According to the Apex Docs, when testing VF you have to set up the current page as follows in your test method:

 

PageReference pageRef = Page.success;   // replace with your page name
Test.setCurrentPage(pageRef);

 after which you can set the parameters.

Rahul SharmaRahul Sharma

Just you need to change to the field names with actual API names as i'm not aware of your data model.

Make that changes and then run the test mehod.

 

Thanks bob, and i'm would like to know if we can set parameter of the current page with that method, 



PageReference pageRef = Page.success;   // replace with your page name 

 

shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com

Hi rahul,

        Api names of feilds are same as shown

i.e UserId,AccountId,TeamMemberRole. Using your solution i am able to pass values from test method to class, but then Adding entries to AccountTeamMember object from front end( vf page) fails.

Thanks

Rahul SharmaRahul Sharma

There must be some criteria/ Validation/Trigger which stops you to save the record.

Check for it.

bob_buzzardbob_buzzard

Yes, once you've done the Test.setCurrentPage call, you can then set parameters via the ApexPages.getCurrentPage().getParameters().put() mechanism.