+ Start a Discussion
bohemianguy100bohemianguy100 

constructor not defined in test method

I'm getting the followig error in my test method:

constructor not defined: [AccountOpenCasesExtension].<Constructor>()

 

I instantiated the class file and called my initialize method that is called within the constructor.  I'm not clear on why the constructor is not defined.  Shouldn't the constructor execute when the class is instantiated?

 

Here is my class file:

 

public class AccountOpenCasesExtension { private List<Account> accounts; public List<Account> getAccounts() { return accounts; } public AccountOpenCasesExtension(ApexPages.StandardController stdController) { init((Account)stdController.getRecord()); //accounts = [Select id, name, (Select Owner.Name, Contact.Name, CaseNumber, Subject, CreatedDate From Cases WHERE IsClosed = false) From Account a WHERE id =: stdController.getId()]; } public void init(Account a) { accounts = [Select id, name, (Select Owner.Name, Contact.Name, CaseNumber, Subject, CreatedDate From Cases WHERE IsClosed = false) From Account a WHERE id =: a.Id]; } static testMethod void test() { Account acct = [Select id, name, (Select Owner.Name, Contact.Name, CaseNumber, Subject, CreatedDate From Cases WHERE IsClosed = false) From Account a LIMIT 1]; AccountOpenCasesExtension ctrl = new AccountOpenCasesExtension(); ctrl.init(acct); } }

 

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

In your testmethod you have the following line:

 

 

AccountOpenCasesExtension ctrl = new AccountOpenCasesExtension();

 

which is an attempt to instantiate the controller through a no-arg constructor.  However, you don't have one of these - you only have the constructor that takes a standard controller.

 

 

This needs to be changed to:

 

 

AccountOpenCasesExtension ctrl = new AccountOpenCasesExtension(new ApexPages.StandardController(account));

 

That way you will be instantiating the controller through the existing controller, plus you won't need to execute the init method explicitly from your testmtehod.

 

 

 

 

 

All Answers

bob_buzzardbob_buzzard

In your testmethod you have the following line:

 

 

AccountOpenCasesExtension ctrl = new AccountOpenCasesExtension();

 

which is an attempt to instantiate the controller through a no-arg constructor.  However, you don't have one of these - you only have the constructor that takes a standard controller.

 

 

This needs to be changed to:

 

 

AccountOpenCasesExtension ctrl = new AccountOpenCasesExtension(new ApexPages.StandardController(account));

 

That way you will be instantiating the controller through the existing controller, plus you won't need to execute the init method explicitly from your testmtehod.

 

 

 

 

 

This was selected as the best answer
Mats ErikssonMats Eriksson

Eff... I try this with the case object and get "Variable does not exist: Case"

 

private class TestDuplicateSerials { static testMethod void myUnitTest() {

DuplicateSerials sc = new DuplicateSerials(new ApexPages.StandardController(Case)); } }

 

 

The referenced class:

public with sharing class DuplicateSerials {

public List<Case> related {get; set;}

public string enabled {get; set;}

public DuplicateSerials(ApexPages.StandardController std) { <Snip> } }

 

The controller class and it's VisualForce Page is working correctly in the test system. I 'just' need to test the controller.

 

/Mats

bob_buzzardbob_buzzard

That's because you don't have a variable called 'case' instantiated earlier in your test class.

 

Might be as simple as:

 

DuplicateSerials sc = new DuplicateSerials(new ApexPages.StandardController(new Case()));

 

Mats ErikssonMats Eriksson

Bingo!!

 

Thanks M8.

 

/Mats

santhossanthos

I am trying to write a test class for the followig controller but it gives me "Constructor not defined" error.

 

public class selectedSizeWorkaround {
   
    ApexPages.StandardSetController setCon;
    public selectedSizeWorkaround(ApexPages.StandardSetController controller) {
        setCon = controller;
    }

 

I tried this but still gives me the same error.

 

selectedSizeWorkaround sswa = new selectedSizeWorkaround(new ApexPages.StandardController(new lead()));
bob_buzzardbob_buzzard

That's because your class has a constructor for a standardsetcontroller defined, but you are passing it a standard controller.  Should be something like:

 

new SelectedSizeWorkaround(new ApexPages.StandardSetController(new List<Lead>(){new Lead(), new Lead()}));

 

santhossanthos

Alright, it worked...

 

Thanks Bob.

Anil DuttAnil Dutt

Hi Bob,

 

i m getting same error

 

Apex class is

 

global class SendConfirmationEmail {

    public SendConfirmationEmail(ApexPages.StandardController controller)
    {
    }
   
    Webservice static void SendEmail(string contactId,string oppId)
    {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setTargetObjectId(contactId);
        mail.setWhatId(oppId);
        mail.setTemplateId('00Xd0000000PFaY');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

 

And Testcase is

 

@isTest
private class SendConfirmationTestCase {
    public static testMethod void myUnitTest() {
        Contact con =  new Contact();
        con.FirstName = 'Anil';
        con.LastName = 'Dutt';
        con.Email = 'anil@swiftsetup.com';
        insert con;
        
        Opportunity oppNew =  new Opportunity();
        oppNew.Name = 'Test Opp';
        oppNew.StageName = 'Ticketing';
        oppNew.CloseDate = System.now().date();
        insert oppNew;
        
        string contactId= con.Id;
        string oppID = oppNew.Id;
        
        ApexPages.StandardController sc = new ApexPages.StandardController(con);
        SendConfirmationEmail sc1 = new SendConfirmationEmail(sc);
        SendConfirmationEmail.SendEmail(contactId, oppID);
    }
}

 

but getting following error

 

Save error: Constructor not defined: [SendConfirmationEmail].<Constructor>(ApexPages.StandardController)

 

will you please find what is wrong here?

thanks

Anil DuttAnil Dutt

Changing

 

ApexPages.StandardController sc = new ApexPages.StandardController(con);

 

to

 

ApexPages.StandardController sc = new ApexPages.StandardController(oppNew);

 

solved the issue

thanks

sunil kumarsunil kumar

Thanks for posting valuable data.

 

thanks

sunil kumar

Adil_SFDCAdil_SFDC

Hi I am getting same error. I tried above methods

 

public class ContactDetails

{
public ID contactId {get; set;}
public String contactName {get; set;}
public String contactEmail {get; set;}
public Boolean isSelected {get; set;}
public ContactDetails(Id conId,String name,String Email)
{
contactId = conId;
contactName = name;
contactEmail = email;
isSelected = false;
}
}

 

Test Method

public static testMethod void testICentera()
{
PageReference pageRef = Page.opportnityicenteraintegration;
Test.setCurrentPage(pageRef);
Opportunity op = new Opportunity(Email__c='adi@abc.com',Name='icentera',StageName='Qualification',CloseDate=date.today());
insert op;
Opportunity o = [select id from Opportunity where id = :op.id];
ApexPages.StandardController sc = new ApexPages.standardController(o);
OpportunityiCenteraIntegration controller = new OpportunityiCenteraIntegration(sc);

 

  OpportunityiCenteraIntegration.contactDetails cd = new OpportunityiCenteraIntegration.contactDetails();

 

Please help

 

 

bob_buzzardbob_buzzard

You can't do this:

 

 OpportunityiCenteraIntegration.contactDetails cd = new OpportunityiCenteraIntegration.contactDetails();

 as you don't have a constructor that takes no arguments.  The constructor you have is:

 

public ContactDetails(Id conId,String name,String Email)

 so you need something like:

 

 Contact cont=new Contact(FirstName='Unit', LastName='Test');
insert cont;
OpportunityiCenteraIntegration.contactDetails cd = new OpportunityiCenteraIntegration.contactDetails(cont.id, 'Unit Test', 'unit.test@unit.test');

 

 

Amit_Amit_

Hi ,

Even I am getting the same error while writting a constructor and my wapper class in my test class .  I am not getting how to solve it. here is my Class-------------

public class ProductDetails {

public ProductDetails(ApexPages.StandardController controller){
           
    }

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;
                    }
      
        }  

       doing some operations and rest of method calls;

}            

here is my test class :

@isTest
 private 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 = True,  Pricebook2Id = p.id , Product2Id  = pro.id , UnitPrice  = 100 ) ;
              insert price;
      //ApexPages.StandardController setCon = new ApexPages.StandardController();
      //ApexPages.currentPage().getParameters().put('id',price.id);
          ProductDetails pd = new ProductDetails (new ApexPages.StandardController());
              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();
    
     }  

Errors:

Constructor not defined: [ApexPages.StandardController].<Constructor>();

 

please give me some solution.

Thanks & Regards

Amit_

Rocks_SFDCRocks_SFDC

I have the test class pasted below:

 

@isTest
Public Class SampleControllerTest{
public static testMethod void LeadConvertTest(){

Account acc=new Account();
acc.Name='Test Account 1';

insert acc;
Contact con=new Contact();
con.AccountId=acc.id;
con.FirstName='Test Contact';
con.LastName='Anil';
con.Phone='5278945';
insert con;

Lead le=new Lead();
le.FirstName='Test Lead';
le.LastName='Anil';
le.Company='Automatic Data Processing';
le.Phone='123456';
le.Status='Sales Review';
le.referred_contact_id__c=con.id;
le.Business_Unit__c='Added Value Services';
le.Lead_Source_New__c='Sales Internal Referral';
insert le;

ApexPages.StandardController std = new ApexPages.StandardController(le);
SampleConvert_Controller wc=new SampleConvert_Controlle(std);
wc.init();
}

}

 

I am getting the following error: Please help me out of this:

Error: Compile Error: Constructor not defined: [SampleConvert_Controlle].<Constructor>(ApexPages.StandardController)

 

Thanks,

Anil

Susheel Reddy BSusheel Reddy B
Hi Bob,

Class
public class MassEditContacts {

    ApexPages.StandardSetController setCon;
    List<string> strIds = new List<string>();
    List<Contact> lstContact = new List<Contact>();
    public integer size {get;set;}
    public final String URL {get;set;}
    public Contact c;
    
    public Contact getNewContact()
    {
      if(c==null)c= new Contact();
      return c;
    }
    public MassEditContacts (Apexpages.Standardsetcontroller cont)
    {
        setCon = cont;
        strIds = ApexPages.currentPage().getParameters().get('recs').split(',',-2);
        size = strIds.size();
        URL = ApexPages.currentPage().getURL();
    
    }
    public List<Contact> getContacts()
    {
        lstContact = [select Name, Title, Phone, MobilePhone, Email, AccountId, ownerid from Contact where id IN: strIds ];
        return lstContact;
    }
     
    public Pagereference saveRecords()
    {
        List<Contact> updateContact = new List<Contact>();
    for(Contact cse : lstContact)
    {
      updateContact.add(cse);
    }
        update updateContact;
        return new Pagereference('/'+Contact.getSObjectType().getDescribe().getKeyPrefix()+'/o');
    }
    
    public Pagereference ccancel()
    {
        system.debug('***ccancel**');
        return new Pagereference('/'+Contact.getSObjectType().getDescribe().getKeyPrefix()+'/o');
    }
}

Test Class:
@isTest
public class TaskControllerExtensionTest
{
Static TestMethod void testSave()
{
Test.startTest();
Account acc = new Account();
acc.Name = 'test account';
insert acc;
Contact cont = new Contact();
cont.firstname = 'test';
cont.lastname = 'contact';
cont.email = 'test@contact.com';
insert cont;

PageReference ref = Page.MassEditContact;
Test.setCurrentPage(ref);
ref.getParameters().put('Ids',cont.id);
Contact con = new Contact();
ApexPages.StandardController ctrl = new ApexPages.StandardController(con);
MassEditContacts ext = new MassEditContacts(ctrl);
List<Contact> tList = ext.getIds();
System.assertEquals(tList.size(),1);
PageReference pg = ext.Save();
ext.getContacts();
ext.ccancel();
if(pg != null) System.assertNotEquals(pg, null);
Test.stopTest();
}
}

Error: Error: Compile Error: Constructor not defined: [MassEditContacts].<Constructor>(ApexPages.StandardController) at line 21 column 24
raju p 4raju p 4
 Hi  i am getting this Error>>>>Constructor not defined,,,,,,
Error: Compile Error: Constructor not defined: [multiselectPicklistAccountANDlead.wrap].<Constructor>(Boolean, Lead) at line 6 column
 Here is my code
public class multiselectPicklistAccountANDlead {
    public list<wrap>ares;
   public list<wrap> ls= new list<wrap>();
   public list<wrap>getares(){
  for(lead l:[select Account_del__r.Id,Account_del__r.Phone,account_del__r.Name,Id,Name,LastName,city,phone from lead limit 5]){
   ls.add(new wrap(false,l));
          
    return ls;
    }
    }
        public class wrap{
           public Boolean sel{set;get;}
           public account ac{set;get;}
           public lead ld{set;get;}
             public wrap(Boolean b,account a,lead l){
              sel=b;
              ac=a;
              ld=l;
             }
        }
}
 please let me know where i am doing Mistake
V J 12V J 12
Thanks @bob_buzzard. Followed your comments in this thread and was able to get my controller tests to work fine.
A Raj 9A Raj 9
Hi All, below test class has similar problem as 'Constructor not defined: [PhaseDeleteAllLinesExt].<Constructor>(ApexPages.StandardController)'. Plz help me out in resolving the issue.

below is test class
*****

@isTest
public class PhaseDeleteAllLinesExtTest {
        
        static testMethod void MyTest()
        {       

            list<opportunity> opp = [select id, name from opportunity where id='0060h000010bfWz'];
            
            Project_Phase_Plan__c  plan = new Project_Phase_Plan__c ();
            plan.Phase_Plan_Description__c = 'Testing';

            insert plan;
            
            Project_Phase__c phase = new Project_Phase__c();
            phase.Project_Phase__c = 1;
            phase.Trade__c = 'Glazier';

            insert phase ;
                        
            PageReference pageRef = Page.ProjectPhaseDeleteAllLines;
            pageRef.getparameters().put('Id', plan.id);
            Test.setCurrentPage(pageRef);
            Apexpages.StandardController sc = new Apexpages.StandardController(plan);

            PhaseDeleteAllLinesExt ext = new PhaseDeleteAllLinesExt(sc);
            ext.deleteAllLines();

           ext.close();

        }
    
         static testMethod void MyTest2()
             {
                 Project_Phase_Plan__c  plan = new Project_Phase_Plan__c ();
                 plan.Phase_Plan_Description__c = 'Testing';ds

                insert plan;

                Project_Phase__c phase = new Project_Phase__c();
                phase.Project_Phase__c = 1;
                phase.Trade__c = 'Glazier';

                insert phase ;

             
            PageReference pageRef = Page.ProjectPhaseDeleteAllLines;
            Test.setCurrentPage(pageRef);
            Apexpages.StandardController sc = new Apexpages.StandardController(plan);

            PhaseDeleteAllLinesExt ext = new PhaseDeleteAllLinesExt(sc);        
            ext.deleteAllLines();     

       ext.close();

        }
    }

*******