Thursday, May 19, 2016

APEX: Instantiating a Constructor with a StandardController Parameter in a Test Class

Suppose you have the following class:

public with sharing class MyClass {
public MyClass(ApexPages.StandardController con) { try { if(con != null) { // your sObject and any other logic here Account acct = (Account)con.getRecord(); } } catch(Exception ex) { system.debug(ex.getMessage() + ' ' + ex.getStackTraceString()); } } public void myMethod(){} }

Then in your test class:
public static testMethod void testMyClass() { try { Test.startTest(); // Create sObject in your own factory class List<Account> accts = TestFactory.createSObject('Account', 1, true); system.assertEquals(accts.size(), 1); PageReference pr = Page.MyPage; Test.setCurrentPageReference(pr);
        ApexPages.currentPage().getParameters().put('qp', 'yyyy');
MyClass mc = new MyClass(new ApexPages.StandardController(accts.get(0))); Test.stopTest(); } catch(Exception ex) { system.debug(ex.getMessage() + ' ' + ex.getStackTraceString()); } }

No comments:

Post a Comment