• richardv
  • NEWBIE
  • 75 Points
  • Member since 2008

  • Chatter
    Feed
  • 3
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 10
    Questions
  • 23
    Replies

Hey guys... I'm geting really frustrated with having to test my classes... but *sigh* SF makes me do it anyways... Here's my problem:

 

I'm trying to test a page reference method that updates child records.

 

 

I've done the following:

 

It saves correctly, but when I run the test I get: 

System.NullPointerException: Attempt to de-reference a null object

 



//Get back to the imaction Manager
PageReference refreshAxnMgr = new PageReference('/apex/IMACtionManager?id=' + thisImc.id);
Test.setCurrentPage(refreshAxnMgr);

//Instantiate and construct the controller class.
ApexPages.StandardController imcCon1 = new ApexPages.StandardController(new IMAC__c());
//extend controller with extension, referencing base controller
ImacController imcExt1 = new ImacController(imcCon1);


//Simulate the {!saveAXNS} expression in the Visualforce page
// by directly calling the saveAXNS method.
String saveAXNS = imcExt1.saveAXNS().getUrl(); <--dereferencing a null object (whatever that means)

 

//It should be back at the manager
System.assertEquals('/apex/IMACtionManager?id=' + thisImc.id, saveAXNS);

 

Here is the method Actual:

 

//Save function for IMACtions - used on IMACtions pageblock public PageReference saveAXNS() { try { update actions; } catch (Exception e) { ApexPages.addMessages(e); } return null; }

 

 

Thanks,

JN

 

 

  • January 05, 2010
  • Like
  • 0

See below class.  If you execute go() either anonymously or as test method, the method call to get() will throw an SObjectException even though a try/catch exists for that exact exeption!  Anyone seen this before?  Seems very much like a defect to me.  Please let me know if you feel the same way.

 


global class DemoExceptionIssue {


    global testmethod static void go(){
        final String BAD_FIELD_NAME = 'namexxxxx';
        try{
            (new Account()).get(BAD_FIELD_NAME);
        }catch(SObjectException e){
            System.debug('SObjectException caught as expected (1)');
        }
        //YIKES!  This next line will throw SObjectException
        //  in Spring '10 even though try/catch is in method!
        get(new Account(),BAD_FIELD_NAME);
    }
   
    global static Object get(SObject sobj, String fieldName){
        try{
            return sobj.get(fieldName);
        }catch(SObjectException e){
            System.debug('SObjectException caught as expected (2)');
        }
        return null;
    }
   
}
 


 

Run this anonymously:

 

Object op1 = new SelectOption('xyz','abc');
System.debug('op1 instanceof SelectOption: ' + (op1 instanceof SelectOption));

 

Any ideas on why this errors out?

I have the following trigger / @future callout which works terrific in the UI.

==============================================================
trigger afterInactivateUser on User (after update) {
 Set<Id> inactivatedParterUsers = new Set<Id>();

 for(Integer i = 0; i < Trigger.new.size(); i++){
  User oldUser = Trigger.old.get(i);
  User updatedUser = Trigger.new.get(i);
  if(updatedUser.ContactId != null && updatedUser.IsActive == false && oldUser.IsActive == true){
   inactivatedParterUsers.add(updatedUser.id);
  }
 }
 if(!inactivatedParterUsers.isEmpty()){
  PartnerUtils.createInactivateUserPartnerRequest(inactivatedParterUsers);
 }
}
==============================================================
==============================================================
public class PartnerUtils {
 @future
 public static void createInactivateUserPartnerRequest(Set<Id> ids){
  List<User> users = new List<User>([select id, ContactId from User where id in :ids]);
  List<MyCustomObject__c> requestList = new List<MyCustomObject__c>();
  MyCustomObject__c request = null;
  for(User user : users){
   request = new MyCustomObject__c();
   request.Contact__c = user.ContactId;
   requestList.add(request);
  }
  insert requestList;
 }

}
==============================================================

However, the following test throws a MIXED_DML_OPERATION when the @future createInactivateUserPartnerRequest() method tries to insert a non-User object:
==============================================================
@IsTest
private class PartnerUtilsTest {
private static testmethod void testAfterInactivateUserTrigger(){
User user = [select id from user where IsActive = true and ContactId != null limit 1];
user.IsActive = false;
update user;
}
}
==============================================================

Any ideas on a workaround that won't fail?

 

I have the following code -

 

====================================================

1        try{

2         List<List<SObject>> searchList = [

3         FIND :searchString IN ALL FIELDS RETURNING 

4         Account (id,IsPartner,name WHERE IsPartner = true ORDER BY name)

5 ];

6 searchResults = ((List<Account>)searchList[0]);

7        }catch(QueryException e){

8         errorTooManySearchResults = true;

9         return null;

10       }catch(Exception e1){

11 ApexPages.addMessages(e1);

12         return null;

13       }        

====================================================

 

-and I'm trying to get 100% test coverage.  Testing lines 1-6 are easy of course; however, I've been unable to figure out a way to test lines 7-12.  A generic Exception should be thrown if :searchString is less that two characters.  I try setting that value to less than two characters but the testing environment seems to ignore that.  Any ideas on forcing generic Exception to be thrown?

 

As far as testing QueryException, the reason I'm catching QueryException is it will be thrown if too many results are returned; and this works great through the UI.  In order to test that, I need to be able to create whatever number of accounts is needed to go over the governor limit.  With the below test, I create 250; however, the SOSL query above only returns 200.  Any ideas forcing the query to return too many rows?

 

 

====================================================

    private static testmethod void testTooManyResultsError() {

List<Account> accounts = new List<Account>();

for(Integer i = 0; i < 250; i++){

accounts.add(new Account(name='Test' +i));

}

insert accounts;

Id[] ids = new Id[accounts.size()];    

for(Integer i = 0; i < accounts.size(); i++){

accounts[i].IsPartner = true;

ids[i] = accounts[i].id;

}

update accounts;

        Test.setFixedSearchResults(ids);

 

        TheController controller = new TheController();

        System.assertEquals(false, controller.errorTooManySearchResults); 

        System.assertEquals(controller.doPageLoad(),null); 

        System.assertEquals(false, controller.errorTooManySearchResults); 

        

        controller.searchString = 'test';

 

        System.assertEquals(controller.doSearch(),null); 

        System.assertEquals(true, controller.errorTooManySearchResults); 

    }

====================================================


 

How do you lookup the IP Address of the current user from Apex/VisualForce?

Private helper methods in test classes count against code coverage (which IMHO is a bad thing).  The below code is not deployable because it's code coverage is only 60%.  Does anyone have an idea for rewriting this code so that the code coverage goes up to 100% (other than moving the code in assertNoErrorMessagesExist method into the test method of course)?

 

======================================= 
public class AController {
 public Id anId {get;set;}
 public AController(){}
 }
}
======================================= 
 
=======================================  
@IsTest
private class TestAController {

 private static testmethod void testControllerWithNoId(){
  AController controller = new AController();
  assertNoErrorMessagesExist();
 }


 private static void assertNoErrorMessagesExist(){
  List<ApexPages.Message> errorMessagesOnly = new List<ApexPages.Message>();
  if(ApexPages.getMessages() != null && ApexPages.getMessages().size() > 0){
   for(ApexPages.Message message : ApexPages.getMessages()){
    if(message.getSeverity() == ApexPages.Severity.ERROR 
     || message.getSeverity() == ApexPages.Severity.FATAL){
     errorMessagesOnly.add(message);
    }
   }
  }
  System.assert(errorMessagesOnly.size() > 0,errorMessagesOnly.size() + ' error(s) exist!');
 }

======================================= 

 

Why is the method Test.setCurrentPage() not listed with the rest of the methods available for the Test class?  

 

See link to Test class doc below:

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_test.htm

 

The only documentation I can find for this method is here:

http://www.salesforce.com/us/developer/docs/pages/Content/pages_controller_error_handling.htm 

I have the following simple VF Page and Controller.  In IE6, clicking on the Continue link throws an error.  Any ideas?

 

==============================

VF Page:

==============================

 <apex:page standardController="Account"
    extensions="TestCommLinkErrorCtrlExt"
    showheader="false" >
    <apex:form >
        <apex:commandLink action="{!doNext}">
            <apex:image value="{!$Resource.RightArrow}"/>&nbsp;Continue
        </apex:commandLink>
    </apex:form>
</apex:page>

 

==============================

Controller Extension

==============================

public class TestCommLinkErrorCtrlExt {
    public TestCommLinkErrorCtrlExt(ApexPages.StandardController c) {}
    public PageReference doNext(){ return null;}
}

Is there a StringBuffer equivalent for Apex?  I don't see one in the API. 

If there is no equivalent, could someone on the Apex Platform team shed some light on performance impacts of using + to append strings? 
I have a trigger that doesn't seem to function the same during a test as it does during normal operation.

Here's my trigger:
========================================
trigger AccountInsertTrigger on Account (before insert, after insert) {
    if (Trigger.isBefore) {
        for (Account account : Trigger.new) {
            account.Description = 'abc 123 456 ' + Datetime.now().getTime();
            System.debug('BeforeInsert: account.Description: ' + account.Description);    
        }
    } else {
        for (Account account : Trigger.new) {
            System.debug('AfterInsert: account.Description: ' + account.Description);    
        }
    }
}
========================================



Here's my test method:
========================================
public class TestAccountInsertTrigger {
    public static testmethod void testCategoryToProjectTypeMapping(){
        Account account = new Account(Name='test');
        System.debug('BeforeTrigger: account.Description: ' + account.Description);    
        insert account;
        System.debug('AfterTrigger: account.Description: ' + account.Description);    
    }
}
========================================



And here's the log output:
========================================
20081017164414.973:Class.TestAccountInsertTrigger.testCategoryToProjectTypeMapping: line 5, column 9: BeforeTrigger: account.Description: null
20081017164414.981:Trigger.AccountInsertTrigger: line 5, column 13: BeforeInsert: account.Description: abc 123 456 1224261854981
20081017164415.016:Trigger.AccountInsertTrigger: line 9, column 13: AfterInsert: account.Description: abc 123 456 1224261854981
20081017164414.973:Class.TestAccountInsertTrigger.testCategoryToProjectTypeMapping: line 7, column 9: AfterTrigger: account.Description: null
========================================


Note the last line of the log output has null for account.Description.

Shouldn't it be "abc 123 456 1224261854981"?


Message Edited by richardv on 10-17-2008 11:10 AM

See below class.  If you execute go() either anonymously or as test method, the method call to get() will throw an SObjectException even though a try/catch exists for that exact exeption!  Anyone seen this before?  Seems very much like a defect to me.  Please let me know if you feel the same way.

 


global class DemoExceptionIssue {


    global testmethod static void go(){
        final String BAD_FIELD_NAME = 'namexxxxx';
        try{
            (new Account()).get(BAD_FIELD_NAME);
        }catch(SObjectException e){
            System.debug('SObjectException caught as expected (1)');
        }
        //YIKES!  This next line will throw SObjectException
        //  in Spring '10 even though try/catch is in method!
        get(new Account(),BAD_FIELD_NAME);
    }
   
    global static Object get(SObject sobj, String fieldName){
        try{
            return sobj.get(fieldName);
        }catch(SObjectException e){
            System.debug('SObjectException caught as expected (2)');
        }
        return null;
    }
   
}
 


 

Hello,

 

I'm getting an error today when trying to save APEX changes in Eclipse:  

 

"Save error: Unable to perform save on all files: PermGen space".

 

Is this a problem in my workspace, or in the SF Org I am developing in?

 

Thank you

Hey guys... I'm geting really frustrated with having to test my classes... but *sigh* SF makes me do it anyways... Here's my problem:

 

I'm trying to test a page reference method that updates child records.

 

 

I've done the following:

 

It saves correctly, but when I run the test I get: 

System.NullPointerException: Attempt to de-reference a null object

 



//Get back to the imaction Manager
PageReference refreshAxnMgr = new PageReference('/apex/IMACtionManager?id=' + thisImc.id);
Test.setCurrentPage(refreshAxnMgr);

//Instantiate and construct the controller class.
ApexPages.StandardController imcCon1 = new ApexPages.StandardController(new IMAC__c());
//extend controller with extension, referencing base controller
ImacController imcExt1 = new ImacController(imcCon1);


//Simulate the {!saveAXNS} expression in the Visualforce page
// by directly calling the saveAXNS method.
String saveAXNS = imcExt1.saveAXNS().getUrl(); <--dereferencing a null object (whatever that means)

 

//It should be back at the manager
System.assertEquals('/apex/IMACtionManager?id=' + thisImc.id, saveAXNS);

 

Here is the method Actual:

 

//Save function for IMACtions - used on IMACtions pageblock public PageReference saveAXNS() { try { update actions; } catch (Exception e) { ApexPages.addMessages(e); } return null; }

 

 

Thanks,

JN

 

 

  • January 05, 2010
  • Like
  • 0

Run this anonymously:

 

Object op1 = new SelectOption('xyz','abc');
System.debug('op1 instanceof SelectOption: ' + (op1 instanceof SelectOption));

 

Any ideas on why this errors out?

Hi,

 

I cannot find anything neither in the documentation nor on the web that answers my question. It is used throughout the batch Apex guide yet there's no formal definition for it. What kind of object is it? What can I do with it?

 

Also how do you access the children retrieved using a QueryLocator like so (it's a relationship query):

 

Database.getQuerylocator([select Id, Name, (select Name from Account) from Contact]);

 

Thanks in advance.

 

  • October 29, 2009
  • Like
  • 0

I have a VF page that uses custom labels, which are translated, and are properly localized when setting the page language via a URL param.  I also have a custom radio button list that uses labels for some of the values, which is created on the fly in the controller.  I'm running into an issue where the VF-included labels are properly grabbing the correct language translation, but the Apex-included labels are not.

 

So...howdo I override the controller itself to be using a specific language, rather than just the VF page?

 

In Apex, you can only call a label via System.Label.labelname , so it seems like it's completely dependent on the user's browsing/set language.  I need this for Sites, so I would like to ensure that the language param passed to the VF page overrides any SF magic/automation on language detection/setting.

UNKNOWN_EXCEPTION, portal account owner must have a role

 

I can not seem to create a customer portal user for my testMethod...has anyone else had success?

 

I really want to runAs() a portal user since the code will be run from there. Currently I'm simply querying for an existing portal user, but that means I have to ensure the same Account/Contact/User are created in every environment including Production and I'd like to avoid having to rely on "dummy" data in Production for my tests to work.

 

I create an account, I create a contact, the account is owned by a user who has a role and profile...but I still get the error above

 

Here is my simplified code (removed personal info, etc) which throws the above error...

 

     static testMethod void Test_getSubjects() {
        Profile pp = [select id from Profile where name LIKE '%Portal%' LIMIT 1];
        Profile sysp = [select id from Profile where name LIKE 'System Administrator' LIMIT 1];
        UserRole r = [select id from UserRole where name = 'CEO' LIMIT 1];
        System.assertNotEquals(null,r);
        User sysU = new User(alias = 'admin',
                    email='admin@testorg.com',
                    emailencodingkey='UTF-8',
                    lastname='Testing',
                    languagelocalekey='en_US',
                    localesidkey='en_US',
                    profileid = sysp.Id,
                    userroleid = r.Id,
                    timezonesidkey='America/Los_Angeles',
                    username='admin@testorg.com');
        insert sysU;
        Account acct = new Account(name='test');
        acct.owner = sysU;
        insert acct;


        User assertUser = [select userroleid from user where id =: acct.ownerId LIMIT 1];

        System.assertNotEquals(null,assertUser.userRoleId);

 

        Contact cont = new Contact();
        cont.lastname = 'test';
        cont.phone = '555-555-5555';
        cont.Account = acct;
        insert cont;
        User u = new User(alias = 'port',
                            email='portaluser@testorg.com',
                            emailencodingkey='UTF-8',
                            lastname='Testing',
                            languagelocalekey='en_US',
                            localesidkey='en_US',
                            profileid = pp.Id,
                            contactid = cont.Id,
                            timezonesidkey='America/Los_Angeles',
                            username='portaluser@testorg.com');
        insert u;
        Test.startTest();
        System.runAs(u) {
            Boolean result = myMethod();

            System.assertEquals(true,result);
        }
        Test.stopTest();
    }

 

Thank you very much. Any and all help is greatly appreciated!

Caleb

Hi Community,

 

I'm creating a visualforce page on opportunity object. My Stage values are dependent on Record type in Opportunity. I need to display the Stage picklist on this new visualforce page but it should contain only the valid picklist values for the particular record type of the Opportunity record. How can I achieve this?

         

       I found this article in which the author is making use of two new custom objects to store the dependency information but I don't want to use this since it is going to be very difficult to maintain it. Is there any workaround for this (using the Metadata API or something)?

  • April 22, 2009
  • Like
  • 0

Hi,

 

I'm trying to use cookies with a visualforce page. I set the cookie with javascript but when I use System.currentPageReference().getHeaders() the returned map doesn't have a 'Cookie' key. Is this because salesforce strips them before they get to us and if so is there a reason for doing this? 

 

Thanks!

Scott 

How do you lookup the IP Address of the current user from Apex/VisualForce?

Why is the method Test.setCurrentPage() not listed with the rest of the methods available for the Test class?  

 

See link to Test class doc below:

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_test.htm

 

The only documentation I can find for this method is here:

http://www.salesforce.com/us/developer/docs/pages/Content/pages_controller_error_handling.htm 

I am creating a simple Java Script to do Bulk Lead Conversion from a list view. I want to ask the user for the Account name to convert the leads to and include that Account name in a Query to see if it already exists. 

 

I can not find the right format to incorporate the Account Name the user inputted to add to my Query. Can someone please help?!

 

var AccountName=prompt("Select Account Name to Convert to",'' ); //this works fine

 

Not sure how to structure the Query to find existing Account names based on Account Name

 

var accts=sforce.connection.query("Select Id, Name from Account where Name like ?????????? ");

Would you please help me to display Notes & Attachments on a Visual Force page having CUSTOM controller ?
Is there any tag for it ?

Hello fellow 'sites-ers'
 
I have an problem where I want to store the users session Id so I can pull back session variables within my apex code. (Goal is to create own authentication process.) Problem is this:
 
I hit the first page UserInfo.getSessionId() returns a sessionId. If I store this in my custom object and go off to my next page; using UserInfo.getSessionId() I get a different session Id.
 
(All UserInffo.getsessionId() method calls are in constructors - not sure if that is important or not...)
 
Why is this? Any ideas? Any soultions?
 
Thanks,
Rich.
 
Hi,

I have a Contract Terms Custom Object which has a dependent picklist named 'Territory' depending on 'Region' picklist. I have used these two picklist in my page using the inputField tag but I am not getting the behaviour of the depending picklist. As soon as I change the Region value, the Territory picklist values should change depending on the value selected but it does not happen.

Here is the piece of code
Code:
        <apex:pageBlock title="Section 2" rendered="{!showSecondSection}">
            <p>To what geography does this rate apply— </p>
             Region: <span style="padding:10px;"/>
             <apex:inputField value="{!contractTerms.REGION__c}"></apex:inputField>
             <p> Territory: <span style="padding:10px;"/>
             <apex:inputField id="territory" value="{!contractTerms.TERRITORY__c}"/></p>
             <p><span style="padding:10px;"/><apex:commandButton action="{!showSection3}" 
value="Continue" styleClass="btn"></apex:commandButton></p><br/> </apex:pageBlock>

 
Can anyone please help me resolve this issue?

Thanks,
Jina