+ Start a Discussion
ClaiborneClaiborne 

Strange Behavior in for loop executing over a query

I have an apex class that executes a for loop based on a query in the initialization class. The code is 
for (UserTerritory2Association uta : [
        select User.AccountId, User.Account.Name,
        User.Account.Regional_Manager__c,
        Territory2.Name, 
        Territory2.ParentTerritory2Id,
        Territory2.ParentTerritory2.Name
        from UserTerritory2Association 
        where user.usertype = 'PowerPartner'
        and Territory2.ParentTerritory2Id != null]) {
        .
        .
        .
    }
The code was developed in a full sandbox, and it executes without problem. And the test code works.

But when I deploy, all of the tests fail because of a failure in the class. The error is:
 
line 30, column 50: Didn't understand relationship 'Account' in field path. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names.
Stack Trace: null

So I shuffled the code to query the list outside of the loop. The new code is:
List<UserTerritory2Association> utaList1 = [
        select User.AccountId, User.Account.Name,
        User.Account.Regional_Manager__c,
        Territory2.Name, 
        Territory2.ParentTerritory2Id,
        Territory2.ParentTerritory2.Name
        from UserTerritory2Association 
        where user.usertype = 'PowerPartner'
        and Territory2.ParentTerritory2Id != null];
    
    for (UserTerritory2Association uta : utaList1) {
        .
        .
        .
    }
This deploys fine.

Any ideas why the first one does not work. 

Also, the query itself works fine in both the full sandbox and production.
 

 
ClaiborneClaiborne
OK, another tidbit. If I deploy and run onl the one test associated with the new class, it deploys without error. 

And run all tests in the sandbox executes without error.
Naval Sharma4Naval Sharma4
Hi Claiborne,

I think error is not with your query. It's somewhere in your code. Can you please post your full test class here.
ClaiborneClaiborne
No, it is not in the code. It deploys fine if I run the single test during deployment. It fails, actually all 55 tests fail because of the error in the routine where the code is. It is doing this before the tests actually run. Weird.