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
richardvrichardv 

Trigger doesn't perform the same during normal operations as in test method

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
ShamSham
Committing a sobject doesn't load values again from database.
The description has been updated in database,not only avaliable in Apex Code, if you load/populate it explicitly.

To see the value..you need to query the Description field. again.

Account act =  [SELECT Id,Description from Account where Id = :account.Id];
System.debug(act.Description) // This will show the value of Description correctly.


richardvrichardv
Thanks Sham, after running a quick test, you're absolutely correct.  I think it's strange behavior though b/c I think of the trigger as performing on the same object and as a result, any setting of values would be propagated forward.  Thanks for the tip.