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
dmsx2oddmsx2od 

system.assertequals says no... but UI says yes - test method failling for no reason

I have this trigger to copy the new owner's last name to the Account site (using standard fields instead of custom ones for simplicity):

 

trigger accountOwnerSalesID on Account (before insert, before update) {
Set<ID> UserIDs = new Set<ID>();
for(Account a : Trigger.New){
UserIDs.add(a.OwnerId);
}
map<ID, String> usermap = new map<ID, String>();
for (User u:[SELECT id, LastName FROM User WHERE id in: UserIDs]){
usermap.put(u.id, u.LastName);
}
for(Account acct: Trigger.New){
acct.Site = usermap.get(acct.OwnerID);
}
}

 And my test code:

 

@isTest
private class testAccountOwnerSalesID {
static testMethod void myUnitTest() {
ID runningID = UserInfo.getUserID();
system.debug(string.valueof(runningID));
User ouruser = [SELECT id, LastName FROM User WHERE id =: runningID LIMIT 1];
String userlastname = ouruser.LastName;
system.debug('userlastname: ' + userlastname);
Account acct = new Account(name='acct1');
insert acct;
system.debug('acct site: '+ acct.Site);
system.assertequals(userlastname, acct.Site);
update acct;
system.debug('acct site: '+ acct.Site);
system.assertequals(userlastname, acct.Site);
}
}

But my assertequals statements fail.  The system says that the Site is null.  But when I create & update an Account in the UI, it works flawlessly for both.

What am I missing?

 

Thanks

 


 

jwetzlerjwetzler
Moving thread to Apex Code forums.
SuperfellSuperfell
Your trigger updates the DB, but your test code never reads back the row from the DB, so acct.site is null.
JimRaeJimRae

What you need to do is capture the ID for the account you create, after the insert in your testmethod.

Then, query for the inserted version of your account, including the account.site field.

Do you assert against that.

 

 

@isTest private class testAccountOwnerSalesID { static testMethod void myUnitTest() { ID runningID = UserInfo.getUserID(); system.debug(string.valueof(runningID)); User ouruser = [SELECT id, LastName FROM User WHERE id =: runningID LIMIT 1]; String userlastname = ouruser.LastName; system.debug('userlastname: ' + userlastname); Account acct = new Account(name='acct1'); insert acct; String acctid=acct.id; Account checkAcct=[select id,Site from Account where id=:acctid limit 1]; system.debug('acct site: '+ checkAcct.Site); system.assertequals(userlastname, checkAcct.Site); update acct; Account checkAcct2=[select id,Site from Account where id=:acctid limit 1]; system.debug('acct site: '+ checkAcct2.Site); system.assertequals(userlastname, checkAcct2.Site); } }