I keep getting a null pointer exception error as follows :
System.NullPointerException: Attempt to de-reference a null object Stack Trace: Class.ColloTest_utoStudentIDTrigger.test_latestStudentID: line 20, column 1
trigger AutoStudentIDTrigger on Contact(before insert) {
list <Contact> l1 =
[SELECT Id, Type_of_bursary_contact__c, Student_ID_New__c, Do_Not_Auto_Generate_Student_ID__c FROM Contact WHERE
Type_of_bursary_contact__c = 'Student'
AND RecordTypeId in (SELECT Id FROM RecordType WHERE Name = 'Bursary Contact') AND Student_ID_New__c != NULL
ORDER BY Student_ID_New__c desc limit 1
];
list <Contact> l2 =
[SELECT Id, Beneficiary_Number__c, Role_in_group__c FROM Contact WHERE
RecordTypeId in (SELECT Id FROM RecordType WHERE Name = 'Community Contact') AND Beneficiary_Number__c != NULL
ORDER BY Beneficiary_Number__c desc limit 1
];
Integer l1size = l1.size();
Integer l2size = l2.size();
Decimal NewLatestStudentID = 0.0;
Decimal NewLatestBeneficiaryID = 0.0;
If(l1size > 0) {
try {
NewLatestStudentID = l1[0].Student_ID_New__c;
}
Catch(System.NullPointerException e) {
System.debug('The following exception has occurred: ' + e.getMessage());
}
}
If(l2size > 0) {
NewLatestBeneficiaryID = l2[0].Beneficiary_Number__c;
}
If(trigger.isInsert) {
for (Contact li: Trigger.new) {
If(li.Type_of_bursary_contact__c == 'Student' & li.Do_Not_Auto_Generate_Student_ID__c == FALSE) {
li.Student_ID_New__c = NewLatestStudentID + 1;
}
If(li.Role_in_group__c != Null & li.Do_Not_Auto_Generate_Beneficiary_Number__c == FALSE) {
li.Beneficiary_Number__c = NewLatestBeneficiaryID + 1;
}
}
}
}
I've tried everything to fix this but I don't understand why this error is occurring. I've instantiated all my variables, when I run my test it works great, why is this happening on deployment? Thanks in advance
Test Code as shown below:
@isTest
private class ColloTest_utoStudentIDTrigger{
static testmethod void test_latestStudentID(){
Test.startTest();
Id BCrtid1 = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('Bursary Contact').getRecordTypeId();
Contact ct1 = new Contact();
ct1.LastName = 'Student Last Name';
ct1.FirstName = 'Student First Name';
ct1.Email = '[email protected]';
ct1.MobilePhone = '0725888886';
ct1.Type_of_bursary_contact__c = 'Student';
ct1.RecordtypeId = BCrtid1;
insert ct1;
system.debug('ct1 inserted');
Id CCrtid1 = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('Community Contact').getRecordTypeId();
Contact cct1 = new Contact();
cct1.LastName = 'Student Last Name';
cct1.FirstName = 'Student First Name';
cct1.Email = '[email protected]';
cct1.MobilePhone = '0725834986';
cct1.Role_in_group__c = 'Secretary';
cct1.RecordtypeId = CCrtid1;
insert cct1;
system.debug('cct1 inserted');
}
}