You need to sign in to do that
Don't have an account?

System.assertEquals not working in test method
Hi,
I am having problems with System.assertEquals method not working in my test method. This is the trigger and the class with testmethod:-
trigger NoOfEmployeesTrigger on Account (before insert, before update)
{
if(Trigger.isInsert)
{
Account[] accs = Trigger.new;
for(Integer i=0; i<accs.size(); i++)
{
if(accs[i].name.contains('19'))
{
accs[i].NumberOfEmployees = 25;
}
else
accs[i].NumberOfEmployees = 75;
}
}
if(Trigger.isUpdate)
{
Account[] accs = Trigger.new;
for(Integer i=0; i<accs.size(); i++)
{
if(accs[i].name.contains('19'))
{
accs[i].NumberOfEmployees = 25;
}
else
accs[i].NumberOfEmployees = 75;
}
}
}
public class NoOfEmployeesClass
{
static testMethod void NoOfEmployeesTest()
{
Account acc1 = new Account(name = 'Vim_19Jun_acc1');
Account acc2 = new Account(name = 'Vim_20Jun_acc2');
test.startTest();
insert acc1;
insert acc2;
System.assertEquals(25, acc1.NumberOfEmployees);
//System.assertNotEquals(acc2.NumberOfEmployees, 25);
acc2.name = 'Vim_19Jun_acc2';
update acc2;
test.stopTest();
}
}
The Number of employees field is a number field and it is giving error there under Test failures section:-
Method Name | Total Time (ms) | Message | Stack Trace |
---|---|---|---|
NoOfEmployeesClass.NoOfEmployeesTest | 126.0 | System.Exception: Assertion Failed: Expected: 25, Actual: null | Class.NoOfEmployeesClass.NoOfEmployeesTest: line 12, column 3 |
However, if I remove the method the test method works successfully giving 100% code coverage.
Please assist!
Thanks,
Vimal
You need to re-query your account objects before you assert. The trigger updates the database record, not the 'in-memory' objects you created to do the insert. Something like:
Account updatedAcc1 = [select Id, NumberOfEmployees from Account where Id = :acc1.Id]
and then assert against updatedAcc1 should do it.
All Answers
You need to re-query your account objects before you assert. The trigger updates the database record, not the 'in-memory' objects you created to do the insert. Something like:
Account updatedAcc1 = [select Id, NumberOfEmployees from Account where Id = :acc1.Id]
and then assert against updatedAcc1 should do it.
Thanks buddy!
It worked! (85% code coverage gained.bugging my head for where exactly can I compensate for those remaining 15%, but yes Salesforce expectation of atleast 75% is achieved happily.... :)) )
-Vimal
Glad I found this solution - working on my first Apex Trigger and Test cases and was wondering why my System.assertEquals were always failing.
Thanks
Debra