4

I'm trying to create a test class for a null record. I have a vf page, and extension, that acts as a form for creating a new record. In my extension constructor I have the following code

public Clinical_Study__c cStudy {get; set;}

public ClinicalStudySetupExtension(ApexPages.StandardController std) {

        this.std = std;

    this.cStudy=(Clinical_Study__c)std.getRecord();
    if (cStudy == null) {
        cStudy = new Clinical_Study__c();
    }

and I have my test class set up like

Clinical_Study__c clinicalStudy = new Clinical_Study__c();
    insert clinicalStudy;


    PageReference pageRef = Page.ClinicalStudySetup;
    pageRef.getParameters().put('query','GA00806'); 
    Test.setCurrentPage(pageRef);

    ApexPages.StandardController sc = new ApexPages.StandardController(clinicalStudy);
    ClinicalStudySetupExtension ext = new ClinicalStudySetupExtension(sc);

The problem is that the line in my constructor "cStudy = new Clinical_Study__c();" is not getting hit when I run the test class. What is the proper way to create a null record in a test class, and then apply it to the ApexPages.StandardController setup in my test class?

  • 2
    I don't believe it is possible. Doing new ApexPages.StandardController(null) will result in a Argument cannot be null error and new ApexPages.StandardController() gives you the following error Constructor not defined: [ApexPages.StandardController].<Constructor>() – BarCotter Feb 19 '15 at 15:50
  • 2
    As a general rule, test methods should be able to test most of your logic. When you have problems testing something in a test method, that suggests that a particular branch of code might never be executed. The exception to this are exceptions, which can be hard to impossible to test. In this case, you need to learn which options can throw exceptions, and what those exceptions may be. – sfdcfox Feb 19 '15 at 16:03
  • Thanks @sfdcfox . Is there a way to set up the ApexPages.StandardController in my test class so that it thinks it's a brand new record (no data, no id, or anything). When I try do something like ApexPages.StandardController = new ApexPages.StandardController(new Clinical_Study__c()); I get almost 0% test coverage. This should be easy, is there something I'm doing wrong? – rwegner7 Feb 19 '15 at 16:45
  • 1
    @rwegner7 That's the correct method; you pass the SC into the constructor. You also need to write code in your test method that will call the methods that will be tested, such as any action methods you may have, etc. – sfdcfox Feb 19 '15 at 17:10
  • 1
    you had it earlier - ApexPages.StandardController sc = new ApexPages.StandardController(new Clinical_Study__c()); – cropredy Feb 19 '15 at 17:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.