function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Joe BrodarJoe Brodar 

MaskTaskController.myUnitTest() Failure on pageRef is null

I attempted to delpoy code from the sandbox to production, but was met with an error that is persistent, and occurs when I run the test seperately from deployment. The test that fails is ABSI_TEST_MassTaskController, and it fails when it reaches the assertion that pageRef cannot be null. The exact error code is:
ABSI_TEST_MassTaskController.myUnitTest(), Details: System.Exception: Assertion Failed: Same value: null Class.ABSI_TEST_MassTaskController.myUnitTest: line 110, column 1

I am completely unable to edit this test code, nor can I edit the class that it should be testing, in fact they are completely absent from the sandbox environment.

The test class (ABSI_TEST_MassTaskController) is:
/******************************************************
 * Description      : Test Coverage for ABSI_MassTaskController (98%)
 * @author          : Malaka Silva
 * @since           : May 07, 2010  
 * Copyright 2010 ABSI. All rights reserved. 
 ******************************************************/
@isTest
private class ABSI_TEST_MassTaskController {

    static testMethod void myUnitTest() {
        Test.startTest();
        
        //Create Accounts
        Account account1 = new Account();
        account1.Name = 'Test_Account_01';
        insert account1;
        
        Account account2 = new Account();
        account2.Name = 'Test_Account_02';
        insert account2;        
        
        //Create Contacts
        Contact contact1 = new Contact();
        contact1.LastName = 'Test_Contact_01';
        insert contact1;
        
        Contact contact2 = new Contact();
        contact2.LastName = 'Test_Contact_01';
        insert contact2;
        
        //Get a profile from SFDC
        Profile profile = [select Id from Profile limit 1];
        
        //Create a user
        User user = new User();
        user.Username = 'Test_user_name@test.com';
        user.LastName = 'Test_last_name';
        user.ProfileId = profile.Id;
        user.Alias = 'tst';
        user.Email = 'Test_email@email.com';
        user.CommunityNickname = 'Test_nick_name';
        user.TimeZoneSidKey = 'GMT';
        user.LocaleSidKey = 'en_US';
        user.LanguageLocaleKey = 'en_US';
        user.EmailEncodingKey = 'ISO-8859-1';
        insert user;
        
        //Simulate the page for What Id
        PageReference pPageReference = Page.ABSI_Mass_Task_Action;
        pPageReference.getParameters().put('objIds',account1.Id+','+account2.Id);
        pPageReference.getParameters().put('retUrl','');
        Test.setCurrentPage(pPageReference);
        
        ABSI_MassTaskController controler = new ABSI_MassTaskController();
        System.assertEquals(controler.showWhoId, true);
        controler.getTableDisplayNames();
        controler.saveNew();
    controler.save();
    controler.back();

        //Simulate the page for Who Id
        pPageReference = Page.ABSI_Mass_Task_Action;
        pPageReference.getParameters().put('objIds',contact1.Id+','+contact2.Id);
        pPageReference.getParameters().put('retUrl','');
        Test.setCurrentPage(pPageReference);
        controler = new ABSI_MassTaskController();
        System.assertEquals(controler.showWhoId, false);
        controler.getTableDisplayNames();
        controler.getselReminderOptions();
        controler.saveNew();
    Pagereference pageRef = controler.save();
      System.assertEquals(pageRef, null);
    controler.back();
    
    controler.task.OwnerId = user.Id;
    controler.task.Subject = 'Test_Subject';
    controler.task.Status = 'Completed';
    controler.task.Priority = 'High';
    //Set the reminder
    controler.task.IsReminderSet = true;
    controler.contact.Birthdate = Date.today();
    controler.reminderTime = '23:30';
    //Send Email notification
    controler.sendNotificationEmailCheckBox = true;
    
    controler.saveNew();
    pageRef = controler.save();
      System.assertNotEquals(pageRef, null);
    
        Test.stopTest();
    }
}

The class it should be testing (ABSI_MassTaskController) is:
/******************************************************
 * Description      : Apex Controller for ABSI_Mass_Task_Action page
 * @author          : Malaka Silva
 * @since           : May 07, 2010  
 * Copyright 2010 ABSI. All rights reserved. 
 ******************************************************/
public with sharing class ABSI_MassTaskController {

    //Capture the values for the standard Task
    public Task task{set;get;}
    //Capture the value for the reminder date/time
    public Contact contact{set;get;}
    public String reminderTime{set;get;}
    //Other Form fields
    public Boolean sendNotificationEmailCheckBox{set;get;}
    public Map <Id,String> displayNames{set;get;}
    private Map <Id,Id> ownerIds;
    public Boolean showWhoId{set;get;}
    public Boolean showPage{set;get;}
    public Boolean assignToOwner{set;get;}
    //Page processing parameters
    private List <Selectoption> selReminderOptions;
    private String [] arrObjIds;
    private String objName = null;
    private Boolean saveStatus;
    private String objPrefix = null;
    
    /**
    * Constructor
    * Initalize the values & generate the object list(Names)
    */
    public ABSI_MassTaskController(){
        //Initalize the variables
        showPage = false;
        task = new Task();
        contact = new Contact();
        displayNames = new Map<Id,String>();
        ownerIds = new Map<Id,Id>();
        showWhoId = false;
        sendNotificationEmailCheckBox = false;
        saveStatus = false;
        assignToOwner = false;
        
        try{
            //Get the object ids passed as parameter
            Map<String, String> params = ApexPages.currentPage().getParameters();
            String strObjIds = params.get('objIds');
            arrObjIds = strObjIds.split(',');
            
            //Identify the object name/type and get the names
            if(arrObjIds != null && !arrObjIds.isEmpty()){
                //Find the object name
                Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe(); 
                Set<String> keyPrefixSet = gd.keySet();
                String tPrefix = arrObjIds[0].subString(0,3);
                
                for(String sObj : keyPrefixSet){
                    Schema.DescribeSObjectResult r =  gd.get(sObj).getDescribe();
                    if(tPrefix.equals(r.getKeyPrefix())){
                        objName = r.getName();
                        objPrefix = tPrefix;
                        break;
                    }
                }
                //Query the name for all the objects
                if(objName != null){
                    String strFieldName = 'name';
                    //Check if the object is a Contact or Lead
                    if(objName != 'Contact' && objName != 'Lead'){
                        showWhoId = true;
                    }
                    //Handle field that doesn't have a name field
                    if(objName == 'Case'){
                        strFieldName = 'CaseNumber';
                    }
                    
                    String strQuery = 'select id,OwnerId,' + strFieldName + ' from ' + objName + ' ';
                    Boolean bFirst = true;
                    for(String strObjId:arrObjIds){
                        if(bFirst){
                            strQuery += ' where Id in (\'';
                            bFirst = false;
                        }else{
                            strQuery += ',\'';
                        }
                        strQuery += String.escapeSingleQuotes(strObjId) + '\'';
                    }
                    strQuery += ')';
                    try{
                        SObject [] sfdcObjects = Database.query(strQuery);
                        //Generate the name list
                        for(SObject sfdcObject:sfdcObjects){
                            displayNames.put((Id)sfdcObject.get('id'),(String)sfdcObject.get(strFieldName));
                            ownerIds.put((Id)sfdcObject.get('id'), (Id)sfdcObject.get('OwnerId'));
                        }
                    }catch(Exception e){
                        strQuery = strQuery.replace(',' + strFieldName, ' ');
                        SObject [] sfdcObjects = Database.query(strQuery);
                        //Generate the Id list instead of name list
                        for(SObject sfdcObject:sfdcObjects){
                            displayNames.put((Id)sfdcObject.get('id'),(Id)sfdcObject.get('id'));
                        }
                    }
                }
            }
            showPage = true;
        }catch(Exception e){
            //Apexpages.addMessage(new Apexpages.Message(ApexPages.severity.ERROR, e.getMessage()));
            Apexpages.addMessage(new Apexpages.Message(ApexPages.severity.ERROR, 'Unexpected error has occured. Please try again later.'));
            showPage = false;
        }
        
    }
    public void assignToOwnerClick(){
        if(assignToOwner){
            assignToOwner = false;
        }else{
            assignToOwner = true;
        }
    }
    /**
    * Save the new task and keep the existing page
    */
    public void saveNew(){
        //Create the new task list
        List <Task> lTask = new List<Task>();
        //Capture the status for save()
        saveStatus = false;
        try{
            for(String strObjId:arrObjIds){
                Task taskNew = new Task();
                
                if(showWhoId){
                    //If the selected objests are not Contacts/Leads
                    taskNew.WhatId = strObjId;
                }else{
                    //If only Contacts/Leads
                    taskNew.WhoId = strObjId;
                }
                //Assign to the record owner based on selected options
                if(assignToOwner){
                    taskNew.OwnerId = ownerIds.get(strObjId);   
                }else{
                    taskNew.OwnerId = task.OwnerId;
                }
                taskNew.status = task.status;
                taskNew.subject = task.subject;
                taskNew.activityDate = task.activityDate;
                taskNew.priority = task.priority;
                taskNew.description = task.description;
                //If the reminder is set
                if(task.IsReminderSet){
                    taskNew.IsReminderSet = true;
                    String [] arrReminderTimes = reminderTime.split(':');
                    Time tmpTime = Time.newInstance(Integer.valueOf(arrReminderTimes[0]), Integer.valueOf(arrReminderTimes[1]), 0, 0);
                    Datetime reminderDateTime = Datetime.newInstance(contact.Birthdate, tmpTime);
                    taskNew.ReminderDateTime = reminderDateTime;
                }
                lTask.add(taskNew);
            }
            //Insert the new tasks to the SFDC Org
            insert lTask;
        }catch(Exception e){
            Apexpages.addMessage(new Apexpages.Message(ApexPages.severity.ERROR, e.getMessage()));
            return;
        }
        
        saveStatus = true;
        Apexpages.addMessage(new Apexpages.Message(Apexpages.Severity.CONFIRM, 'Task(s) successfully created.'));
        //Send email
        if(sendNotificationEmailCheckBox){
            sendMail(lTask);
        }
    }
    /**
    * Save the new task and to back to the previous page 
    * (If no errors)
    */
    public Pagereference save(){
        saveNew();
        if(saveStatus){
            return back();
        }
        return null;
    }   
    /**
    * Send email to the assigned engineer
    */
    private void sendMail(List <Task> lTask){
        try{
            //Set mail parameters
            //Query the assigned user
            User assignedUser = [Select u.Name, u.Email From User u where u.Id =: task.OwnerId];
            //Prepare the mail message
            Messaging.Singleemailmessage singleMail = new Messaging.Singleemailmessage();
            singleMail.setToAddresses(new String[]{ assignedUser.Email });
            singleMail.setSubject(task.subject);
            //Generate the HTML body and the plain text body
            String strText = 'To: ' + assignedUser.Name + '<br/><br/>';
            strText += System.Userinfo.getName() + ' has assigned you the following task(s):<br/><br/>';
            strText += 'Subject: ' + task.subject + '<br/><br/>';
            strText += objName + ':<br/>';
            
            String strPlainText = 'To: ' + assignedUser.Name + '/n/n';
            strPlainText += System.Userinfo.getName() + ' has assigned you the following task(s):/n/n';
            strPlainText += 'Subject: ' + task.subject + '/n/n';
            strPlainText += objName + ':/n';
            
            //Put the tasks with objects ids
            Map <Id,Id> mObjectTask = new Map<Id,Id>();
            for(Task newTasks:lTask){
                if(showWhoId){
                    mObjectTask.put(newTasks.WhatId, newTasks.Id);
                }else{
                    mObjectTask.put(newTasks.WhoId, newTasks.Id);
                }
            }
            for(Id displayKey:displayNames.keySet()){
                String displayName = displayNames.get(displayKey);
                Id taskId = mObjectTask.get(displayKey);
                strText += '-' + displayName;
                strText += ' (<a href=\'http://na1.salesforce.com/' + taskId  + '\'>';
                strText += 'http://na1.salesforce.com/' + taskId  + '</a>)';
                strText += '<br/>';
                
                strPlainText += '-' + displayName;
                strPlainText += ' (http://na1.salesforce.com/' + taskId  + ')';
                strPlainText += '/n';
            }
            strText += '<br/>Priority: ' + task.Priority + '<br/><br/>';
            
            strPlainText += '/nPriority: ' + task.Priority + '/n/n';
            
            //Set the test message to the mail
            singleMail.setHtmlBody(strText);
            singleMail.setPlainTextBody(strPlainText);
            //Send the mail
            Messaging.sendEmail(new Messaging.Singleemailmessage [] { singleMail });
        }catch(Exception e){
            //Capture if unexpected error occurs - such as Salesforce mail limit
            Apexpages.addMessage(new Apexpages.Message(ApexPages.severity.ERROR, 'Task(s) added. Mail not sent.'));
        }   
    }
    
    /**
    * Insert in the ReminderDate List the Time : Hours:Min
    */ 
    public List<SelectOption> getselReminderOptions(){
        selReminderOptions = new List<SelectOption>();
        String val = '' ; 
        for (Integer i = 0 ; i < 24 ; i++){
            // Draw the options to add to the reminder picklist 
            val = i+':'+'00';           
            selReminderOptions.add(new SelectOption(val,val));
            val = i+':'+'30';
            selReminderOptions.add(new SelectOption(val,val));
        }
        return selReminderOptions;    
    } 
    /**
    * Go to the previous page
    */
    public Pagereference back(){
        Pagereference pageRef = new Pagereference('/' + objPrefix);
        pageRef.setRedirect(true);
        return pageRef;
    }
    /**
    * Display the selected object names in front end
    */
    public List <String> getTableDisplayNames(){
        List <String> rtnList = new List<String>();
        
        for(String displayName:displayNames.values()){
            rtnList.add('-' + displayName);
        }
        return rtnList;
    }    
    
}

After searching this forum, I was only able to find one reference to this issue, and the suggested solution was to edit the test code. I am unable to deploy any code to production, and so far I have been unsuccessful in finding any documentation on successfully solving the issue here or on third party forums like StackExchange. Any suggestions are welcome.

Thanks,

Joe
Joe BrodarJoe Brodar
P.S. I wanted to include the coding of the VF page that this class is controlling. I do have editing access to this page.
<!--/******************************************************
 * Description      : Visual Force Page for Mass Task Action
 * @author          : Malaka Silva
 * @since           : May 24, 2010  
 * Copyright 2010 ABSI. All rights reserved. 
 ******************************************************/-->
<apex:page id="pg_mass_task" controller="ABSI_MassTaskController" showHeader="true" sidebar="true"  tabStyle="Task">

    <apex:sectionHeader id="section_header" title="Task" subtitle="New Task"/>

    <apex:form id="frmSubmitMassTask">
            
        <apex:messages />
        
        <apex:pageBlock title="New Task" mode="Edit" id="field_section" rendered="{!showPage}">      
     
            <apex:pageBlockSection title="Task Information" id="section01" columns="2">
                <apex:inputField value="{!task.ownerid}" id="owner" rendered="{!NOT(assignToOwner)}"/> 
                <apex:pageblockSectionItem rendered="{!assignToOwner}">
                    <apex:outputLabel value="Assigned To"/>
                    <apex:inputtext disabled="true"/>
                </apex:pageblockSectionItem>
                <apex:pageblockSectionItem >
                    <apex:outputLabel value="Assign Task to Owner" title="Assign Task to Record Owner"/>
                    <apex:inputCheckbox value="{!assignToOwner}" title="Assign Task to Record Owner">
                        <apex:actionSupport action="{!assignToOwnerClick}" event="onchange" immediate="true"/>
                    </apex:inputCheckbox>
                </apex:pageblockSectionItem>
                <apex:inputField value="{!task.status}" required="true" />                 
                <apex:pageblockSectionItem >
                    <apex:outputLabel value="Related To:" />
                    <apex:outputPanel >
                        <div id='spanDisplayLabel' style='width:250px; height:30px; overflow-y:scroll;'>
                            <apex:dataTable value="{!tableDisplayNames}" var="tableDisplayName" >
                                <apex:column value="{!tableDisplayName}"/>
                            </apex:dataTable>                    
                        </div>
                    </apex:outputPanel>
                </apex:pageblocksectionItem>                
                <apex:inputField value="{!task.subject}" required="true" />  
                <apex:pageBlockSectionItem />             
                <apex:inputField value="{!task.activityDate}" />
                <apex:pageBlockSectionItem />
                <apex:inputField value="{!task.priority}" />                             
            </apex:pageBlockSection>

            <apex:pageBlockSection title="Additional Information" columns="1" id="section02">
                <apex:inputField value="{!task.description}" />
            </apex:pageBlockSection>

            <apex:inputCheckbox value="{!sendNotificationEmailCheckBox}" id="sendNotificationEmailCheckBox" /> Send Notification Email
        
            <apex:pageblockSection title="Reminder" id="reminder_section" columns="1">
                <apex:pageBlockSectionItem id="isRemSet">
                    <apex:outputLabel value="Reminder" for="task__IsReminderSet" />
                    <apex:pageBlockSectionItem id="reminder_section_1">
                        <apex:inputField id="task__IsReminderSet" value="{!task.IsReminderSet}" onclick="togglereminder(this.checked);" />
                        <apex:pageBlockSectionItem id="reminder_section_1">
                            <apex:inputField id="task__ListDate" value="{!contact.Birthdate}"/>
                            <apex:selectList id="task__ListTime" value="{!reminderTime}" size="1" styleclass="FormDataASmaller">
                                <apex:selectOptions id="reminder_time_options" value="{!selReminderOptions}" />
                            </apex:selectList>
                        </apex:pageBlockSectionItem>
                    </apex:pageBlockSectionItem>
                </apex:pageBlockSectionItem>
                
            </apex:pageblockSection>
            
            <apex:pageblockButtons id="blockButtons">
                <apex:commandButton value="Save" action="{!save}" id="btnSave" />
                <apex:commandButton value="Cancel" action="{!back}" immediate="true" id="btnCancel"/>
            </apex:pageblockButtons>
            
        </apex:pageBlock>
    </apex:form>
    <script type="text/javascript">
        function assignUser(){
            var objCtr = document.getElementById('pg_mass_task:frmSubmitMassTask:field_section:section01:owner');
            objCtr.disabled = true;
            objCtr = document.getElementById('pg_mass_task:frmSubmitMassTask:field_section:section01:owner_lkwgt');
            objCtr.disabled = true;            
        }
        function togglereminder(blnStatus){
            if(blnStatus){
                var objCtr = document.getElementById('pg_mass_task:frmSubmitMassTask:field_section:reminder_section:isRemSet:reminder_section_1:reminder_section_1:task__ListDate');
                objCtr.disabled = false;
                objCtr = document.getElementById('pg_mass_task:frmSubmitMassTask:field_section:reminder_section:isRemSet:reminder_section_1:reminder_section_1:task__ListTime');
                objCtr.disabled = false;                
            }else{
                var objCtr = document.getElementById('pg_mass_task:frmSubmitMassTask:field_section:reminder_section:isRemSet:reminder_section_1:reminder_section_1:task__ListDate');
                objCtr.disabled = true;   
                objCtr = document.getElementById('pg_mass_task:frmSubmitMassTask:field_section:reminder_section:isRemSet:reminder_section_1:reminder_section_1:task__ListTime');
                objCtr.disabled = true;                           
            }
        }
        togglereminder(false);
        
        function getFieldByID(strControlID){return document.getElementById(strControlID);}
        
        function adjustDisplayArea(){
            try{
                var objControlFake = getFieldByID('spanPlaceHolder') ;
                if (objControlFake.offsetParent) {
                    var objControl = getFieldByID('spanDisplayLabel') ;
                    objControl.style.height = '90px';
                    objControl.style.position = 'absolute';
                    objControl.style.left = objControlFake.offsetLeft + 'px';
                    objControl.style.top= objControlFake.offsetTop + 'px';
                }  
            }catch(e){}
        }
        adjustDisplayArea();
        window.onresize = function(){
            adjustDisplayArea();
            setTimeout('adjustDisplayArea();',300);
            setTimeout('adjustDisplayArea();',500);
            setTimeout('adjustDisplayArea();',1000);
        }        
    </script>
</apex:page>