+ Start a Discussion
Jan Kopejtko 2Jan Kopejtko 2 

Testing class for the simpliest of codes

Hey guys, I've got a very simple trigger:
 
trigger TF on Account (before update, before insert) {
    for (Account a: trigger.New) {
        a.TestField__c = 'test';
    }

}

I wrote a test class for it:
 
@isTest
public class TFTest {
    @isTest static void testName() {
       Account cat = new Account();
        cat.Name = 'cat';
        insert cat;
        System.assertEquals('test', cat.TestField__c);
       }

}
When I run the test, I get an error:
 
Error Message	System.AssertException: Assertion Failed: Expected: test, Actual: null
Stack Trace	Class.TFTest.testName: line 7, column 1

I have two questions:
1) What am I doing wrong?
2) How come my trigger does not need to be tested and works already? I added an Account record already and the field gets populated.

Have a nice day


 
Best Answer chosen by Jan Kopejtko 2
Vinoth Vijaya BaskerVinoth Vijaya Basker
Hello Jan, 

Can you please try the updated code given below. 
@isTest
public class TFTest {
    @isTest static void testName() {
       Account cat = new Account();
        cat.Name = 'cat';
        insert cat;
	Account catInserted = [SELECT TestField__c FROM Account WHERE Id = :cat.Id];	
        System.assertEquals('test', catInserted.TestField__c);
       }

}

Thanks,
Vinoth

All Answers

Vinoth Vijaya BaskerVinoth Vijaya Basker
Hello Jan, 

Can you please try the updated code given below. 
@isTest
public class TFTest {
    @isTest static void testName() {
       Account cat = new Account();
        cat.Name = 'cat';
        insert cat;
	Account catInserted = [SELECT TestField__c FROM Account WHERE Id = :cat.Id];	
        System.assertEquals('test', catInserted.TestField__c);
       }

}

Thanks,
Vinoth
This was selected as the best answer
RahulRahul
@isTest
public class TFTest {
    @isTest static void testName() {
       Account cat = new Account();
        cat.Name = 'test';
        insert cat;
        System.assertEquals('test', cat.Name);
       }

}
RahulRahul
1)AssertEquals checks the above value "cat.Name" is equal to test or not.In your code it was not so it was failing. Your value "cat.TestField__c" does not return expected result that is "test"
2)Every trigger works if written correctly. If you need to deploy a trigger into Production, you need a minimum code coverage of 75%
Jan Kopejtko 2Jan Kopejtko 2
Thanks everyone