[SalesForce] Error on testclass: System.NullPointerException: Attempt to de-reference a null object

Why do i get this error:

System.NullPointerException: Attempt to de-reference a null object

My testclass looks like:

    @isTest
public class attachPDFTestClass { 

  static Account testAccount;
  static {
    testAccount = new Account();
    testAccount.Name = 'REALIANCE';
    insert testAccount;
  }  

    static testMethod void testAttachments() { 
 system.debug('line 2'); 
    //system.debug('id Testaccount: '+testAccount.id);
 system.debug(testAccount.Id); 

    Facturatie__c testFactuur = new Facturatie__c();
    system.debug('line 3'); 
    system.debug(testAccount.Name);
    testFactuur.Accountname__r.Name = testAccount.Name;  
 system.debug('line 4');
    insert testFactuur;
 system.debug('id testFactuur: '+testFactuur.id);


system.debug(testAccount.Name);  is ok

Best Answer

You can't insert your Account outside your test method and access it directly.

You have two solutions:

  • Add a test setup method which inserts the account. Then request this account from your test method
  • Insert your account at the start of your test method like this:

static testMethod void testAttachments() { 
    Account testAccount = new Account();
    testAccount.Name = 'REALIANCE';
    insert testAccount;

 system.debug('line 2'); 
    //system.debug('id Testaccount: '+testAccount.id);
 system.debug(testAccount.Id); 

    Facturatie__c testFactuur = new Facturatie__c();
    system.debug('line 3'); 
    system.debug(testAccount.Name);
    testFactuur.Accountname__c = testAccount.Id;  
 system.debug('line 4');
    insert testFactuur;
 system.debug('id testFactuur: '+testFactuur.id);


system.debug(testAccount.Name);  is ok
Related Topic