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
Amit_Amit_ 

How to write test class for wrapper class

I have a Vf controller class which has a wrapper class and does operation like search based on some criteria, and insert a record to table. now I'll have to write a test class form my controller class. please help me out I am very new to writting Test class. here is snippet of my code though I have not followed a good pratice while writing code i ma doing it for my learning purpose. here is what I have done in Controller ;


public class ProductDetails {


/* ****************  Default Constructor start **************** */

    public ProductDetails(ApexPages.StandardController controller) {

    }
   
/* ****************  Default Constructor End ****************   */


    public void productAddToList(){
       
        set<id> prid =  new set<id>();
        if(string.isNotBlank(ProductPrice) ==False){ 
            if(string.isNotBlank(ProductName)== True){
                lstProd= [select Name,Category__c,id,ProductCode  from product2 where  Name like  :'%' +ProductName+ '%'];
            }
            else if(string.isNotBlank(productCategory)==True){
                lstProd = [select Name,Category__c,id,ProductCode  from product2 where  Category__c like:'%' +productCategory+ '%'];
            }
                else if(string.isNotBlank(ProductCode)==True){
                   lstProd = [select Name,Category__c,id,ProductCode  from product2 where ProductCode like :'%'+ProductCode+'%'];
                }
        for(product2 po : lstprod){
            prid.add(po.id);
            prname.add(po.Name);   
        }
        pricebke = [select Product2Id,UnitPrice from pricebookentry where Product2Id in :prid and UseStandardPrice=True];
       
        for(product2 product : lstprod){
            for(pricebookentry price : pricebke){
                if(product.id==price.Product2Id){
                    ProductWarpper prodwap = new ProductWarpper();
                    prodwap.prodObj= product;
                    prodwap.pricebookObj=price;
                    //prodwap.quantity=1;
                    prodwap.totalPrice=price.UnitPrice;
                    prodwap.amount = integer.valueOf(price.UnitPrice);
                    prodwap.isSelected = False;
                    lsPwr.add(prodwap);
                }
            }
        }
       
            
             ProductName= null;
             productCategory = null;
             ProductCode = null;
             ProductPrice =  null;     
        }
        else {
            prc= decimal.valueOf(ProductPrice);
            pricebke = [select Product2Id,UnitPrice from pricebookentry where UnitPrice = :prc and UseStandardPrice=True];
            for(pricebookentry pbkebtry : pricebke ){
                prid.add(pbkebtry.Product2Id);
            }
            lstProd= [select Name,Category__c,id,ProductCode  from product2 where  id in :prid ];
            for(product2 product : lstprod){
                for(pricebookentry price : pricebke){
                    if(product.id==price.Product2Id){
                        ProductWarpper prodwap = new ProductWarpper();
                        prodwap.prodObj= product;
                        prodwap.pricebookObj=price;
                        //prodwap.quantity=1;
                        prodwap.totalPrice=price.UnitPrice;
                        prodwap.amount = integer.valueOf(price.UnitPrice);
                        prodwap.isSelected = False;
                        lsPwr.add(prodwap);
                    }
                }
            }
         
            ProductName= null;
            productCategory = null;
            ProductCode = null;
            ProductPrice =  null;  
          }
    }       
    public void removeRef(){
        for(ProductWarpper cCon: selectedProd){           
                if(cCon.isSelected == false) 
                {                       
                removedProd.add(cCon);
                }                          
            }
       
   
    }
    public pageReference calAmount(){
                   
        return null;
   
    }              
    public list<ProductWarpper> getProdName(){
               productAddToList();                      
       return lsPwr;
    }
                                            
/* ****************    login to add Selected product to kart Start ****************    */ 
   
    public PageReference selectedValue() {
           totalcall();
           for(ProductWarpper cCon:lsPwr){           
                if(cCon.isSelected ==true) 
                { 
                    kartWrapper kartwrp = new kartWrapper();
                    kartwrp.prdlist = cCon;
                    kartList.add(kartwrp);
                    selectedProd.add(cCon);
                }
                cCon.isSelected = False;                          
            }          
         return null;
        }

/* ****************    login to add Selected product to kart End ****************    */ 
/*  ****************   method to redirect page to Oder Page to display the list of Items odered start ****************   */

     public PageReference myAccount(){
            PageReference pageRef = new PageReference('/apex/MyOrderAccount');   
            pageRef.setRedirect(true);       
            return pageRef;
     }
/*  ****************    method to redirect page to Oder Page to display the list of Items odered End ****************   */                                      
/* ****************    Declearing the Wrapper Class start **************** */       
        public class ProductWarpper{
       
        public pricebookentry  pricebookObj {get;set;}
        public Product2 prodObj{get;set;}
        public boolean isSelected {get;set;}
        public integer quantity {get;set;}
        public integer amount{get;set;}
        public decimal totalPrice{get;set;}
        public decimal totalamount {get;set;}
        public decimal getTotal(){
            system.debug('WrapperQuantity    '+this.quantity+    'WrapperPrice    '+ this.totalPrice);
            totalamount = this.quantity * this.totalPrice;
            return totalamount;
        }
      
        }                          
        public  class kartWrapper{
            public ProductWarpper prdlist{get;set;}
        }
   
/* ****************    Declearing the Wrapper Class End ****************  */
       public void totalcall(){
           for (ProductWarpper wrap : selectedProd)
           {
                 System.debug('Total = ' + wrap.getTotal());
           }
       }
/* ****************    Login to search Product based on search key Start ****************    */ 
 
        public PageReference search() {
       
            lsPwr.clear();
            removedProd.clear();
            productAddToList();
           
            return null;     
       
        }
        public PageReference searchProduct(){
       
            search();
            return null;   
        }
/* ****************    Login to search Product based on search key End ****************    */
        public PageReference cancel(){
            lsPwr.clear();
            selectedProd.clear();
            return null;
         }   
/* ****************    Login to Insert and create order start ****************    */
     
       public void OrderPlaced(){
           list<Product2> prodlist = new list<product2>();
               for(ProductWarpper pw : lsPwr){
                   prodlist.add(pw.prodObj);
               }
               OrderItem__c odrt = new OrderItem__c();
               insert odrt;
               list<OrderItem__c>soqlid =[select id from OrderItem__c order by createddate desc];
                   system.debug('get OderId' + soqlid);
                   list<Order__c> orderlist = new list<order__c>();
                   for(ProductWarpper pw : selectedProd){
                   Order__c odr = new Order__c();
                       odr.OrderItem__c = soqlid[0].id;
                       odr.Product2__c =  pw.prodObj.id;
                       odr.OrderCategory__c = pw.prodObj.Category__c;
                       odr.Price__c = pw.pricebookObj.UnitPrice;
                       odr.Quantity__c = pw.quantity;                      
                       orderlist.add(odr);
                   }
                   insert orderlist;
                   selectedProd.clear();
                   lsPwr.clear();
       }
/* ****************    Login to Insert and create order End ****************    */
/* ****************    Login to Remove Items from the Kart start ****************    */
                                    
        public PageReference removeItem(){
            removeRef();
            selectedProd.clear();
        return null;       
        }
        public void editMethod(){}
        public void remove(){
            removeRef();
            selectedProd.clear();

        }
/* ****************    Login to Remove Items from the Kart End ****************    */
      
/* ****************    login to Render Pageblock Sections Start ****************   */       
        public boolean getfirstSection(){
            boolean render =( lsPwr==null || lsPwr.size() ==0? false : true);
            return render;
        }
        public boolean getRendered(){
        Boolean render = (selectedProd== null || selectedProd.size() == 0 ? false : true);
       
        return render;
        }
        public boolean getremovedProdRender(){
            boolean render = (removedProd == null || removedProd.size()==0? false : true);
            return render;
        }
      
/* ****************    login to Render Pageblock Sections End ****************   */
                

    public PageReference methodOne() {
        return null;
    }
                
    public void setState(string n) {
        state = n;
    }
    public void setrestate(string n) {
        restate = n;
    }       
    public string getrestate() {
        return restate ;
    }               
    public string getState() {
        return state;
    }   
    public string state = 'False';
    public string restate = 'True';
   
   
    public void delRow()
    {
        rowNum = Integer.valueOf(apexpages.currentpage().getparameters().get('index'));
        selectedProd.remove(rowNum);  
   
    }
}

 

how will do the code coverage for my code please suggest me.

Thanks & Regards

Amit_

Sri549Sri549

HI

This may be the  test class which you may looking for on product object

public class ProductDetails
{
 public static  void testProductDetails()
 {    
      Pricebook2 p = new Pricebook2 (Description ='Sampleone',Name  = 'Sample');
      insert p;
      Product2  pro = new Product2 (Family ='Scrap',Name='Steel');
      insert pro;
      PricebookEntry price  = new PricebookEntry (UseStandardPrice = false,  Pricebook2Id = p.id , Product2Id  = pro.id , UnitPrice  = 100 ) ;
      insert price;
      //ApexPages.StandardController setCon = new ApexPages.StandardController(price);
      ApexPages.currentPage().getParameters().put('id',price.id); 
      ProductDetails pd =new ProductDetails();
      pd.productAddToList();
      pd.removeRef();
      pd.calAmount();
      pd.ProdName();
      pd.selectedValue(); 
      pd.myAccount();
      ProductDetails.ProductWarpper pdpw=new ProductDetails.ProductWarpper(); 
      pdpw.totalcall();
      pdpw.search();
      pdpw.searchProduct();
      pdpw.cancel();
      pdpw.OrderPlaced();
      pdpw.removeItem();
      pdpw.remove();
      pdpw.firstSection();
      pdpw.Rendered();
      
      
      
      
 }
 
}

 i have covered probably all the methods

if there are any methods pls add and see for best coverage

 

Thanks

Srinivas

 

Amit_Amit_
Hi Sri,
Thanks for your reply, I have used to code for my controller class but I am getting error at once place : at this line

ProductDetails.ProductWarpper pdpw=new ProductDetails.ProductWarpper();
as Compile Error: Invalid type: ProductDetails.ProductWarpper
can you suggest why I am getting this error. and where I should write my Test Class as in a separate class or should i include it my controller. thanks again for your reply
Regards,
Amit_
Amit_Amit_
Hi Sri ,
I am getting error while defining constructor as well
on this line : ProductDetails pd =new ProductDetails();
it is throwing error like -
Compile Error: Constructor not defined: [ProductDetails].<Constructor>() ;
I wrote it inside my controller class.
Rajesh SriramuluRajesh Sriramulu

Hi

 

Could u post ur updated test class.

 

Regards,

Rajesh.

Amit_Amit_
Hi Sri ,
I have just copy pasted your code to check if its working for me, while saving the code I am getting those two errors:
1st One :
ProductDetails.ProductWarpper pdpw=new ProductDetails.ProductWarpper();
as Compile Error: Invalid type: ProductDetails.ProductWarpper
2nd:
ProductDetails pd =new ProductDetails();
Compile Error: Constructor not defined: [ProductDetails].<Constructor>() ;

i am not changing any thing from your code.

Thanks & Regards,
Amit_


Sri549Sri549

Hi

You need to paste the code in the class where you have write Apex class by removing the first line of my sample test class.

ProductDetails.ProductWarpper pdpw=new ProductDetails.ProductWarpper();

this line indicates that mainclass.wrapper class pdpw(Instance of class).

 

Thanks

Srinivas

Amit_Amit_

Hi Sri,
I have written my testclass inside my controller but I dont understand why I keep getting this is error for this line
ProductDetails pd =new ProductDetails();
Compile Error: Constructor not defined: [ProductDetails].<Constructor>() ;
This is the way I have defined my constructor in my class ..


    public ProductDetails(ApexPages.StandardController controller) {

    }