1

I am trying to test for the below controller but I am struggling to write statement for covering user and territories.

Please help me in correcting testclass which is below

@istest
public class TestDM_Approval_New
{
    public static testmethod void approvalmethod()
    {
    //Profile    
      // Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 

      //User
    /*  User u = new User(Alias = 'standt', Email='standarduser@testorg.com', 
                        EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
                        LocaleSidKey='en_US', ProfileId = p.Id, department = 'STP',
                        TimeZoneSidKey='America/Los_Angeles', UserName=Math.random() + '@test.com');

      System.runAs(u) { */
      // The following code runs as user 'u'  

      //Asserting Values
      // System.debug('Current User: ' + UserInfo.getUserName());
     // System.debug('Current Profile: ' + UserInfo.getProfileId()); 
        User userId1 = [SELECT id,name,UserSubmit__c,User_Status__c FROM USER WHERE id =:UserInfo.getUserId()];

          account account9= new account(OwnerId=userId1.id,Name='Plan',BillingStreet='Unit Test Street',BillingCity='Unit Testville',billingstate='Unit Test State',BillingPostalCode='UTEST1 1UT',Description='Unit Test Desc',Account_First_Name__c='Unit test Account First',Active__c='No',Account_Last_Name__c='Unit test Account Last',Specialization_differential__c='PM',Territory_Name__c='Unit test Terr',Approval__c='Pending',Submit__c=true,Called_By_Other_Physicians__c=30, Reason_For_Change__c='Died',DM_updated_flag__c=true,Notes__c='testwq');
       insert account9;
      account accnt= new account(Name='Plan',Active__c='No',BillingStreet='Unit Test Street',BillingCity='Unit Testville',billingstate='Unit Test State',BillingPostalCode='UTEST1 1UT',Description='Unit Test Desc',Account_First_Name__c='Unit test Account First',Account_Last_Name__c='Unit test Account Last',Specialization_differential__c='PM',Territory_Name__c='Unit test Terr',Approval__c='Approved',Submit__c=true,Called_By_Other_Physicians__c=30,
                                        Reason_For_Change__c='Died',DM_updated_flag__c=true,Notes__c='testwq',OwnerId =userId1.id);
     insert accnt;
        Call_String__c call=new Call_String__c(Account__c=accnt.id,Call_String_Status__c='New',Original_CallString__c=1,Primary__c='Arexone',Secondary__c='Methanel',Updated_CallString__c=1);
           insert call;

        DM_Approval_New  deve=new DM_Approval_New ();

        deve.getAbsolute_Pde_change();
        deve.getChange_Pde_Percent();
        deve.getOrgBENICAR_Percent();

        deve.getUser_Territory ();
        deve.getUser_Status();
        deve.getRepname();
        deve.getReptype();
        deve.getTotalAccounts();
        deve.getUpdatedHTNvar();
        deve.getGreen_Upper_limit();
        deve.getGreen_Lower_limit();
        deve.getRed_Upper_limit();
        deve.getRed_Lower_limit();
        deve.getPDElow();
        deve.getPDEhigh();
       // deve.Approve_All();

        /* account account= new account(Name='MICHAEL SHRAMOWIAT',Active__c='yes',Specialization_differential__c='PHA',Approval__c='Approved',Submit__c=False,Is_CallsUpdated__c=False);
           insert account;
           Call_String__c call=new Call_String__c(Account__c=account.id,Call_String_Status__c='New',Original_CallString__c=1,Primary__c='Arexone',Secondary__c='Methanel',Updated_CallString__c=1);
           insert call;*/
         //deve.Approve_All();
   // }
    }
    /* public static testMethod void approvalmethod1(){
         Profile p = [SELECT Id,name FROM Profile WHERE Name='Salesforce'];
         User u = new User(Alias = 'standt', Email='standarduser@testorg.com', 
                            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
                            LocaleSidKey='en_US', ProfileId=p.id,TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com');
         insert u;
         account accnt= new account(Name='Plan',Active__c='No',BillingStreet='Unit Test Street',BillingCity='Unit Testville',billingstate='Unit Test State',BillingPostalCode='UTEST1 1UT',Description='Unit Test Desc',Account_First_Name__c='Unit test Account First',Account_Last_Name__c='Unit test Account Last',Specialization_differential__c='PM',Territory_Name__c='Unit test Terr',Approval__c='Pending',Submit__c=true,Called_By_Other_Physicians__c=30,
                                        Reason_For_Change__c='Died',DM_updated_flag__c=true,Notes__c='testwq',OwnerId=u.id);
         insert accnt;
         DM_Approval_New  deveapp=new DM_Approval_New ();

    }   */
}

Controller Code

public class DM_Approval_New {

public string mail{get;set;}


   Public list<Territory> Territorylist {get;set;}

    public string approveid{get;set;}
    public string rejectid{get;set;} 
    public string UserpassId{get;set;} 
    Public String Callstringid{get;set;}
    Public String RejCallstringid{get;set;}
    public  AggregateResult submitcount;
    Public  Integer TotalSumbittedacc;

//========================Actions For Getting Dyanmic Territories ===========================

list< Dynamic_territory_differential>  Dynamiclist {get;set;} 

Dynamic_territory_differential d1;

public DM_Approval_New ()
                {

                   getdynamicdifferential();
                }

 public list<  Dynamic_territory_differential> getdynamicdifferential()
             {
                    Dynamiclist = new list< Dynamic_territory_differential>();
                    UserTerritory ustr = [Select TerritoryId ,UserId From UserTerritory where UserId = :UserInfo.getUserId()];

                    Map<Id, Territory> terrMap = new Map<Id, Territory>([SELECT Id ,name FROM Territory where ParentTerritoryId =:ustr.TerritoryId ]); 

                    Map<Id, UserTerritory> userTerritoryMap = new Map<Id, UserTerritory>{};
                    Map<Id, User> userMap = new Map<Id, User>{};

                    Set<Id> userIds = new Set<Id>{};

                    for (UserTerritory user : [ SELECT Id, UserId,TerritoryId FROM UserTerritory where TerritoryId IN :terrMap.keySet() ])
                    {
                           userIds.add(user.UserId);
                           userTerritoryMap.put(user.TerritoryId, user);
                    }

                    for (User usr : [ SELECT Id, name,UserSubmit__c,User_Status__c,Original_Plan_Sumbit_Flag__c FROM User where Id IN :userIds  ])
                    {

                           userMap.put(usr.id, usr);
                    }

    for(Territory terr : terrMap.values())
                {         
                        UserTerritory user = userTerritoryMap.get(terr.Id);
                        User userdata =  userMap.get(user.UserId);
                        d1= new Dynamic_territory_differential();
                        d1.TerritoryId = terr;
                        d1.userTerrid = user;
                        d1.username = userdata;
                        Dynamiclist.add(d1);

                }

     return Dynamiclist;

 }

//===================================================================== For Rendering Two Sections Of Rep Changes===========================
list<Account> conlist = new list<Account>();
list<Account> Calllist = new list<Account>();

public void contactdetails()
            {
                    system.debug('UserpassId======='+UserpassId);
                    id UserpassId=apexpages.currentpage().getparameters().get('UserpassId');

                   User usr = [select id,name,UserSubmit__c,User_Status__c FROM User where id = :UserpassId ];
                   if(usr.User_Status__c == 'Approved')
                   {

                    Calllist=[select id,name,Active__c,Approval__c,Specialization_differential__c,Billingcity,Billingstate, OwnerId ,(select id,name,Original_CallString__c,Updated_CallString_plist__c,Call_String_Status__c from Call_Strings__r where Call_String_Status__c='Approved') from Account WHERE OwnerId =:UserpassId and DM_updated_flag__c = true and Callupdate_flag__c = True];
                    conlist=[select id,name,Active__c,Specialization_differential__c,Reason_For_Change__c ,Reason_Drop_Code__c,Approval__c,Reason_Add_Code__c,Billingcity,Billingstate,Original_Calls_Total__c,Notes__c, OwnerId from Account WHERE OwnerId = :UserpassId and Approval__c='Approved'and DM_updated_flag__c =true ];
                       CP_Indicaters();   
                   }
                  else{

                    conlist=[select id,name,Active__c,Specialization_differential__c,Reason_For_Change__c ,Reason_Drop_Code__c,Approval__c,Reason_Add_Code__c,Billingcity,Billingstate,Original_Calls_Total__c,Notes__c, OwnerId from Account WHERE OwnerId = :UserpassId and Approval__c='Pending'and Submit__c=True ];
                    Calllist=[select id,name,Active__c,Approval__c,Specialization_differential__c,Billingcity,Billingstate, OwnerId ,(select id,name,Original_CallString__c,Updated_CallString_plist__c,Call_String_Status__c from Call_Strings__r where Call_String_Status__c='Pending') from Account   WHERE OwnerId =:UserpassId and Submit__c=True and  Callupdate_flag__c = True];
                    CP_Indicaters();     
                   }
           }

public list<Account> getconlist()

            {
                 return conlist;
            }

public list<Account> getCalllist()

            {
                 return Calllist;
            }


Public  Integer getTotalSumbittedacc()
             {
                 return TotalSumbittedacc;
             }


//===========================================================  Actions For Showing Traffic Lights and Percentage Of Product Change Rules Of Reps =======================          

public User UserData;
public integer Green_limits=0;
public integer Red_limits=0;
public integer Green_Upper_limit=0;
public integer Green_Lower_limit=0;
public integer Red_Upper_limit=0;
public integer Red_Lower_limit=0;
public integer Total_PDEvar=0;
public integer PDEhigh=0;
public integer PDElow=0;
public integer UpdatedHTN =0;
public integer WELCHOL_Pde=0;
public Integer AZOR_Pde =0;
public Integer BENICAR_Pde =0;
public integer TRIBENZOR_Pde =0;
public integer TotalAccounts=0;
public AggregateResult Total_Pde;
Public String User_Territory;
Public string Repname;
Public String Reptype;
Public String User_Status;
public boolean  Original_cplan_flag{get;set;}

Public String  BENICAR_Percent ;
Public  String  TRIBENZOR_Percent;
Public  String  Welchol_Percent;
Public String  AZOR_Percent;

Public String   OrgBENICAR_Percent ;
Public  String  OrgTRIBENZOR_Percent;
Public  String  OrgWELCHOL_Percent;
Public String  OrgAZOR_Percent;

Public integer OrgHTN_Percent;
Public integer HTN_Percent; 
Public integer Original_Total_Pde=0; 



public void CP_Indicaters()

    {

       UserData=[select  name,Total_PDE__c,Original_Accounts__c,Territory_Name__c,Original_Plan_Sumbit_Flag__c,Rep_Type__c,User_Status__c,AZOR_PDEs__c,BENICAR_PDEs__c,TRIBENZOR_PDEs__c,WELCHOL_PDEs__c from user where id=:UserpassId];

            Repname = String.valueof(UserData.name);
            Reptype = String.valueof(UserData.Rep_Type__c);
            User_Status = String.valueof(UserData.User_Status__c);
                }
Public integer  Change_HTN_Percent = 0;
Public integer  Changed_WELCHOL_percent=0;
Public integer  getChanged_WELCHOL_percent()
        {
            return Changed_WELCHOL_percent;
        }     
Public integer  getChange_HTN_Percent()
        {
            return Change_HTN_Percent;
        }      

Public integer Updated_Accounts = 0;
Public integer  getUpdated_Accounts()
        {
            return Updated_Accounts;
        }   
public AggregateResult  Droppedacc;
public integer DroppedCount;
public integer getDroppedCount(){

        Droppedacc=[select count(id) from account where Approval__c='Pending' and callplantounierse__c=true and ownerid= :UserpassId];
        DroppedCount = Integer.valueOf(Droppedacc.get('expr0'));
        return DroppedCount;
    }

Public String Change_Pde_Percent='0';  
Public integer Absolute_Pde_change = 0;
Public integer  getAbsolute_Pde_change()
        {
            return Absolute_Pde_change;
        }

public  String  getChange_Pde_Percent()
        {
            return Change_Pde_Percent;
        }    

        public  String  getOrgBENICAR_Percent()
        {
            return OrgBENICAR_Percent;
        }    
        public  String  getOrgTRIBENZOR_Percent()
        {
            return  OrgTRIBENZOR_Percent;
        }    
        public  String  getOrgWELCHOL_Percent()
        {
            return OrgWELCHOL_Percent;
        }    
        public  String  getOrgAZOR_Percent()
        {
            return  OrgAZOR_Percent;
        }    
        public  String  getAZOR_Percent()
        {
            return AZOR_Percent;
        }    
        public  String  getBENICAR_Percent()
        {
            return BENICAR_Percent;
        }    
        public  String  getTRIBENZOR_Percent()
        {
            return  TRIBENZOR_Percent;
        }    
     public  String getWELCHOL_Percent()
        {
            return WELCHOL_Percent ;
        }       

public  integer getTotal_PDEvar()
        {
          return Total_PDEvar;
        }
public  integer getHTN_Percent()
        {
            return HTN_Percent;
        }         
public  integer getOriginal_Total_Pde ()
        {
            return Original_Total_Pde ;
        }        

public  integer getOrgHTN_Percent()
        {
            return OrgHTN_Percent ;
        }         
public  integer getWELCHOL_Pde()
        {
            return WELCHOL_Pde;
        }
Public String getUser_Territory ()
        {
            return   User_Territory; 
        }  
Public String getUser_Status()
        {
            return  User_Status; 
        }        
Public String getRepname ()
        {
            return  Repname; 
        } 
Public String getReptype()
        {
            return  Reptype ; 
        }        
public  integer getTotalAccounts()
        {
            return TotalAccounts;
        }    
public  integer getUpdatedHTNvar()
        {
            return UpdatedHTN;
        }      
public integer getGreen_Upper_limit()
        {
            return Green_Upper_limit;
        }
public integer getGreen_Lower_limit()
        {
            return Green_Lower_limit;
        }
public integer getRed_Upper_limit()
        {
            return Red_Upper_limit;
        }
public integer getRed_Lower_limit()
        {
            return Red_Lower_limit;
        }  

public  integer getPDElow()
        {
            return PDElow;
        }      
public  integer getPDEhigh()
        {
            return PDEhigh;
        }   




//=========================================== Actions of Approving for Add / Drop and Call Frequency Updates============================================================


public void Approve_All()
         {
           list<account> acclist = [select id,name,Active__c,Specialization_differential__c,Reason_For_Change__c ,Approval__c,DM_updated_flag__c,Billingstate,Notes__c  from Account  WHERE OwnerId=:UserpassId and Approval__c='Pending'and  Submit__c=True];
           for(Account doc : acclist)
                   {
                    if(doc.Active__c=='No')
                       {
                          doc.Active__c='No';
                          doc.Approval__c='Approved';
                          doc.DM_updated_flag__c =true;
                          doc.Is_CallsUpdated__c=False; 
                          doc.Submit__c=False;
                           update doc;
                       } 
                    else
                        {
                           doc.Active__c='Yes';                 
                           doc.Approval__c='Approved';
                           doc.DM_updated_flag__c =true;
                           doc.Is_CallsUpdated__c=False;
                           doc.Submit__c=False; 
                           update doc;
                        }

                   }


            list<String__c> app_call = [ Select id,name,Call_String_Status__c from String__c where Call_String_Status__c='Pending' and Account__r.ownerid=:UserpassId];
            list<account> accountlist = [select id,name,Active__c,Approval__c,DM_updated_flag__c,Callupdate_flag__c,Specialization_differential__c,(select id,name,Original_CallString__c,Updated_CallString_plist__c,Call_String_Status__c from Call_Strings__r where Call_String_Status__c='Pending') from Account WHERE OwnerId=:UserpassId and Callupdate_flag__c = True and Submit__c=True];
            list<account> doclist = new list<account>();
            for(String__c doc: app_call)
                    {

                      doc.Call_String_Status__c='Approved';
                      update doc;

                   }

            for(Account acc:accountlist )
                    {
                        acc.Submit__c=false;
                        acc.DM_updated_flag__c =true;
                      //  acc.Callupdate_flag__c = false;
                        doclist.add(acc); 
                    }
                  update  doclist;

              submitcount = [SELECT count(id)  FROM Account where Submit__c=True And OwnerId =:UserpassId];
              TotalSumbittedacc = Integer.valueOf(submitcount.get('expr0'));  
               If( TotalSumbittedacc == 0)
                   { 
                       List<User> Submitflag = [select UserSubmit__c,User_Status__c from user where  Id=:UserpassId];
                       for( User usr : Submitflag )
                                   {
                                        usr.User_Status__c = 'Approved';
                                        Update usr;           
                                   }      
                   }         

                        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                        mail.setTargetObjectId(UserpassId);
                        string body = 'Your Callplan changes have been reviewed.Please chek the approved records.';
                        mail.setSubject('CallPlan Review');
                        mail.setHtmlBody(body); 
                        mail.setSaveAsActivity(false);
                        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });


        Calllist=[select id,name,Active__c,Approval__c,Specialization_differential__c,Billingcity,Billingstate, OwnerId ,(select id,name,Original_CallString__c,Updated_CallString_plist__c,Call_String_Status__c from Call_Strings__r where Call_String_Status__c='Approved') from Account WHERE OwnerId =:UserpassId and DM_updated_flag__c = true and Callupdate_flag__c = True];
        conlist=[select id,name,Active__c,Specialization_differential__c,Reason_For_Change__c ,Reason_Drop_Code__c,Approval__c,Reason_Add_Code__c,Billingcity,Billingstate,Original_Calls_Total__c,Notes__c, OwnerId from Account WHERE OwnerId = :UserpassId and Approval__c='Approved'and DM_updated_flag__c =true ];
        getconlist();
        CP_Indicaters();


  }   


//====================================  Actions of Rejecting for Add / Drop and Call Frequency Updates=================================    


  //=================================Reopen Sumbit Button For User=======================================
 public list<String__c> ListTotalAcc;
 public list<DM_Reviewed__c> ListReviewedAcc;
  public list<DM_Reviewed__c> List_DeleteReviewedAcc;
    public Void Reopen() {


   List_DeleteReviewedAcc = [select id,name from DM_Reviewed__c where Ownerid=:Userpassid];
   Delete List_DeleteReviewedAcc;

   ListReviewedAcc = new list<DM_Reviewed__c>();
   DM_Reviewed__c acc ;


  ListTotalAcc =[select id,name,Updated_CallString_plist__c,Call_String_Status__c, Original_CallString__c,account__r.Total_PDE__c,account__r.Reason_Add_Code__c,Account__r.Reason_Drop_Code__c,Account__r.BENICAR_Target_Value__c,Account__r.Account_First_Name__c,Account__r.name ,Account__r.Account_Last_Name__c,Account__r.AZOR_Rollup__c,Account__r.BENICAR_Rollup__c,Account__r.TRIBENZOR_ROLLUP__c,Account__r.WELCHOL_ROLLUP__c,Account__r.Active__c,Account__r.Total_Calls_Formula__c,Account__r.Specialization_differential__c,Account__r.Territory_Name__c,Account__r.Approval__c,Account__r.Account_Middle_Name__c ,Account__r.BillingpostalCode,Account__r.Ownerid  from String__c where Account__r.Ownerid=:UserpassId]; 
   for(String__c doc:ListTotalAcc )
           {
                         acc = new DM_Reviewed__c();

                        acc.Call_Sequence__c             =       doc.name;
                        acc.CallSequence_Status__c       =       doc.Call_String_Status__c;
                        acc.Original_Calls__c            =       doc.Original_CallString__c;
                        acc.Updated_Calls__c             =       doc.Updated_CallString_plist__c;
                        acc.Account_Status__c            =       doc.Account__r.Approval__c;
                        acc.BillingpostalCode__c         =       doc.Account__r.BillingpostalCode;
                        acc.Name                         =       doc.Account__r.name ;
                        acc.Ownerid                      =       doc.Account__r.Ownerid;
                        acc.Active__c                    =       doc.Account__r.Active__c;
                        acc.Physician_First_Name__c      =       doc.Account__r.Account_First_Name__c;
                        acc.Physician_Last_Name__c       =       doc.Account__r.Account_Last_Name__c;
                        acc.Physician_Middle_Name__c     =       doc.Account__r.Account_Middle_Name__c;
                        acc.Territory_Name__c            =       doc.Account__r.Territory_Name__c;
                        acc.Total_Calls__c               =       doc.Account__r.Total_Calls_Formula__c;
                        acc.Specialty__c                 =       doc.Account__r.Specialization_differential__c;
                        acc.Total_PDE__c                 =       doc.account__r.Total_PDE__c;
                        acc.Reason_Add_Code__c           =       doc.account__r.Reason_Add_Code__c;
                        acc.Reason_Drop_Code_c__c        =       doc.Account__r.Reason_Drop_Code__c;

                        ListReviewedAcc.add(acc);                

            }

       insert ListReviewedAcc;

       User usr= [select Name,UserSubmit__c,User_Status__c,Original_Plan_Sumbit_Flag__c from user where  Id=:UserpassId];

            usr.UserSubmit__c = false;
            usr.Original_Plan_Sumbit_Flag__c = false;
            usr.User_Status__c = '';
            Update usr;           



      getconlist();    
      getCalllist();
    }


 }
  • Is there a specific portion of code you are having trouble getting or are you asking for a full test class to cover everything? We can help you with the first, but not the second. – dphil Jun 17 '15 at 18:28
2

My first suggestion is that you write your test class for testing in bulk. In essence, create "lists" of users, accounts, contacts, etc using for loops. You can use a for(i=0;i<sz;i++) strategy, then set the sz to any integer value. Initially you may only want to test for 1 sample, but later you'll have what you need to test for 100 or more. In doing that, you've written both bulk and single sample test code at the same time.

Oh, and for some things, you may want to use sz1 and sz2 in your code (in your case, sz1 for users, sz2 for accounts and perhaps even a sz3 for contacts, depending on your test design such as the case of having multiple contacts for each account). Be sure to locate those variables at the top of your test class for easy access. Some people even put them in a custom setting.

Now, on to your actual question. It appears from looking at your test class, that after you create your user and account (as I mention below, you're also missing contacts), you need to insert the following code:

test.startTest because this is when your actual testing begins. Prior to doing that though, and this is why you probably need to create lists of users, even if you only have a list of one, it appears that you need to create a list of user Id's, territories, etc that you can later use for creating your system.assertEquals statements.

Another important thing I see is that you've not created any lists of contacts for your accounts. That appears to be an essential part of what your controller returns. All of those related fields and custom account fields need to be included in your accounts and contacts when you create them. Again, one of the important reasons for creating lists.

Hopefully, that should get you started and on your way. Without seeing the Visual Force Code the controller is intended to be used for, its rather difficult for me to give you much more input. I think these things should put you on the right track though towards moving forward on completing a test class. Once all the data has been submitted, You'll then want to use a test.stopTest and do assertions on what the controller returns to make certain you got back what you expected.

At certain points during your testing, its also often wise to make assertions that the data you have is what you expect. That can be very helpful in troubleshooting any problems with your test class. If you get a failure, you can replace the assertion with a system debug statement plus add additional ones at key places above, to locate the source of your problem, then either comment them out or delete them after you've found the source.

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.