I am writing a unittest for a pagereference where I add some variables I currently get only 47% coverage. How do I pass the variables correctly.

I currently get the error: System.NullPointerException: Attempt to de-reference a null object


 public with sharing class EscrowLogin {
    public string username{get;set;}
    public string password{get;set;}
    public PageReference retURL{get;set;}
    List<EscrowValidator__mdt> ev = [SELECT Username__c , Pass__c, Acces_granted__c, Token__c FROM EscrowValidator__mdt];
    public PageReference validateCredentials() {
        map<string,string> tokens = new map<string,string>();        
        for(integer x=0;x<ev.size();x++){
        for(integer x=0;x<ev.size();x++){
            if(username.equals(ev[x].Username__c) && password.equals(ev[x].Pass__c)){
                PageReference retURL = new PageReference('/apex/escrowlink');
                retURL.getParameters().put('token', tokens.get(ev[x].Username__c));
                system.debug('tokens.get(ev[x].Token__c): '+ tokens.get(ev[x].Username__c));
                return retURL; 
            if(!username.equals(ev[x].Username__c) && !password.equals(ev[x].Pass__c) && ev.size() == x+1) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,'Login Error'));
        return null; 


public class EscrowloginTest {
    public string username{get;set;}
    static testmethod void escrow(){  
        Account acct = new Account(Name='testAccount');  
        insert acct;
        EscrowValidator__mdt ev = new EscrowValidator__mdt(Username__c='test',Pass__c='pass',Token__c='123456');            

        PageReference pageRef = Page.EscrowLogin;
        system.debug('pageRef: '+pageRef);
        EscrowLogin controller = new EscrowLogin();
        System.assertEquals(controller.validateCredentials(), pageRef);        

1 Answer 1


Well, you don't seem to be instantiating the username and password variables in your controller during the test. So when you call validateCredentials() in your test, the controller doesn't know what to do when you check if the username and password inputted on the page match one of the credentials in your metadata types.

Might want to try using these lines in your test, before calling the method:

controller.username = 'username';
controller.password = 'password';

Besides this, you should know that you can't insert custom metadata types in an unit test. Given this nature, you will be able to make your test pass only if you have a custom metadata with those values in your org.

Insert Custom Metadata for Unit Test


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .