There might be a lot of other ways to achieve what I am trying to do here but for practice I am using trigger.
The trigger is to update a field acc_number__c
in contact if the finalize_number__c
field is checked. the value is update from a account field also named acc_number__c
.
The trigger worked so now to understand class testing this is what I did. but the test run fails every time. What am I doing wrong?
Error
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Accnumberupdate3: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Class.accnumberupdateclss.replacer: line 17, column 1 Trigger.Accnumberupdate3: line 5, column 1: []
Test Class
@istest
public class Accnumberupdate3test {
Static testmethod void test(){
//give in the values
Contact con = new Contact(LastName='TestRun1', Finalize_Number__c=true);
System.debug('Acc number before insert : ' + con.acc_number__c);
// insert the values
insert con;
con = [SELECT acc_number__c FROM Contact WHERE Id =:con.Id];
System.debug('Acc number after insert : ' + con.acc_number__c);
}
}
Trigger
trigger Accnumberupdate3 on contact (before insert) {
// create a new contact object to pass through the class method
contact[] allconlist = trigger.new;
//pass it in the method
accnumberupdateclss.replacer(allconlist);
}
Trigger Handler
public class accnumberupdateclss {
public static void replacer(contact[] allconlist){
//get all ids for contacts recieved
Set <id> ids = new set<id>();
for( contact c : allconlist){
ids.add(c.accountId);}
//get all account ids
Map<ID, Account> mapacc = new Map<ID, Account>([SELECT acc_number__c,id FROM Account WHERE id IN :ids]);
for(contact c: allconlist ){
if(c.Finalize_Number__c == true){
Account related = new account();
related = mapacc.get(c.accountid);
c.Acc_Number__c = related.acc_number__c;
}
}
}
}
}