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
sfdcJonsfdcJon 

Catch is always called in Try/Catch from Test Method

Hi Guys! I have an issue where a Try/Catch ALWAYS goes to the Catch when invoked from a test method. When invoked from Visualforce as normal this doesn't happen, so it has to be something in the test scenario.

 

It's the second SOQL statement below, which uses a field 'User_Contact_Link__c from the User. This is just a text field containing a Contact ID that matches a Contact record in the system.

 

Any ideas?????

 

Snippet below:

 

u = [SELECT SAG_Account_Creator__c,
                    SAG_Organization__c,
                    SAG_License_Country__c,
                    User_Contact_Link__c
             FROM User
             WHERE id = :UserInfo.getUserId()
             LIMIT 1];

ID convertToLong = u.User_Contact_Link__c;
        String longId = convertToLong;
 
        system.debug('++++UserCon'+u.User_Contact_Link__c);
        system.debug('++++Long'+longId);
        
        try{
            c = [SELECT Id
                        FROM Contact
                        WHERE id = :longId
                        LIMIT 1];system.debug('++++cid'+c.id);}
        catch(QueryException e2){error=TRUE;}

 

Best Answer chosen by Admin (Salesforce Developers) 
rocwilcoxrocwilcox

Expanding on SLockard.  If you dont want to create test data in your test, then use the "SeeAllData=true" option to allow your tests to see data in the org.

This changed in behaviour occured in api v22 (if i recall right)

 

@isTest(SeeAllData=true)

 

 

All Answers

SLockardSLockard

Have you inserted any test data before this? Test classes can't see your 'real' data anymore so you have to insert a contact so that SOQL query actually returns something.

rocwilcoxrocwilcox

Expanding on SLockard.  If you dont want to create test data in your test, then use the "SeeAllData=true" option to allow your tests to see data in the org.

This changed in behaviour occured in api v22 (if i recall right)

 

@isTest(SeeAllData=true)

 

 

This was selected as the best answer
sfdcJonsfdcJon

Thanks to both of you! I had inserted a test user and contact, and was using system.runas(testUser). I think I need to brush up on that, because it wasn't working.

 

However, adding '(SeeAllData=true)' to the '@istest' did the trick.

 

Thank you both, again!