+ Start a Discussion
Ryan GreeneRyan Greene 

test apexpages.standardcontroller

Hello,
I have not written Apex Tests before (I probably should have) and I am running into an error each time I run the test, but there is no error on the page. Test Class below and I am receiving the error on line 6: Error Message - System.NullPointerException: Attempt to de-reference a null object  Stack Trace - Class.Test_UploadAttachmentController.testattach
 
@isTest
private class Test_UploadAttachmentController {
    static testMethod void testattach(){
        Document__c doc = new Document__c(Document__c = 'Aging', RecordTypeId = [SELECT Id, SobjectType, Name FROM Recordtype WHERE Name = 'Request' AND SobjectType = 'Document__c' LIMIT 1].Id);
        insert doc;
        UploadAttachmentController controller = new UploadAttachmentController(new ApexPages.StandardController(doc));
        
        controller.fileName = 'Unit Test Attachment Body';
        controller.fileBody = Blob.valueOf('Unit Test Attachment Body');
        controller.processUpload();
        
        LIST<Attachment> attch = [SELECT Id, Name FROM Attachment WHERE parent.id =: doc.Id];
        System.assertEquals(1, attch.size());
    }
}

 
Best Answer chosen by Ryan Greene
Alain CabonAlain Cabon

PageReference myVfPage = Page.MyVFPName;
Test.setCurrentPage(myVfPage); // Put Id into the current page Parameters
ApexPages.currentPage().getParameters().put('id',doc.id);
UploadAttachmentController controller = new UploadAttachmentController(newApexPages.StandardController(doc));
 

All Answers

Alain CabonAlain Cabon
You should post the tested class. The controller could need other data.
insert doc;  seems to be working but the controller could need other initialiazed values and we cannot guess them.

 System.NullPointerException: Attempt to de-reference a null object  : the controller wants to use a variable but it is not initialized

Very common:
    List<MyObject> myList; without myList = new List<MyObject>(); for instance
   // use of myList => error  System.NullPointerException
or
    MyObject myobj = [SELECT with a request returning nothing so null];
    myobj.myfield;
// error

Regards
Ryan GreeneRyan Greene
Yes I should have. I did find a couple errors in the Class which I corrected; the original error I posted about is now solved.

Please help with the new error I am receiving!

The new error is line 15 of the Test Class: Error Message    System.AssertException: Assertion Failed: Expected: 1, Actual: 0
Stack Trace    Class.Test_UploadAttachmentController.testattach: line 15, column 1

So an Attachment is not being set through the test

I'm at 65% code coverage with this test, so any other tips would be much appreciated!
 
@isTest
private class Test_UploadAttachmentController {
    static testMethod void testattach(){
        Document__c doc = new Document__c(Document__c = 'A/P Aging', RecordTypeId = [SELECT Id, SobjectType, Name FROM Recordtype WHERE Name = 'Request' AND SobjectType = 'Document__c' LIMIT 1].Id);
        insert doc;
        doc = [SELECT Id,Document__c,RecordTypeId, Name FROM Document__c WHERE Id = :doc.Id];
        
        UploadAttachmentController controller = new UploadAttachmentController(new ApexPages.StandardController(doc));
        
        controller.fileName = 'Unit Test Attachment Body';
        controller.fileBody = Blob.valueOf('Unit Test Attachment Body');
        controller.processUpload();
        
        LIST<Attachment> attch = [SELECT Id, Name FROM Attachment WHERE parent.id =: doc.Id];
        System.assertEquals(1, attch.size());
    }
}
 
public class UploadAttachmentController {
    public String description {get;set;}
    private Document__c doc {get;set;} 
    public String fileName {get;set;}
    public Blob fileBody {get;set;}
    public String retst {get;set;}{
        if(String.isBlank(ApexPages.currentPage().getParameters().get('retURL'))){
        	retst = ApexPages.currentPage().getParameters().get('retURL');
        }else{
            retst = 'www.google.com';
        }}
    public Id getid {get;set;}{
        getid = ApexPages.currentPage().getParameters().get('id');}
    public UploadAttachmentController(ApexPages.StandardController cntrl) { 
        this.doc = (Document__c)cntrl.getRecord();
    }   
    private Database.SaveResult saveStandardAttachment(Id parentId) {
        Database.SaveResult result;
        Attachment attachment = new Attachment();
        attachment.body = this.fileBody;
        attachment.name = this.fileName;
        attachment.parentId = parentId;
        attachment.Description = description;
        result = Database.insert(attachment);
        fileBody = Blob.valueOf(' ');
        return result;
    }
    public PageReference processUpload() {
        try {
            Database.SaveResult attachmentResult = saveStandardAttachment(getid);
            if (attachmentResult == null || !attachmentResult.isSuccess()) {
                ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 
                  'Could not save attachment. Please try again or contact the Salesforce Administrator for assistance. Attachment to Notes&Attachments did not process'));            
                return null;
            } else {
                Document__c customAttachment = [select id from Document__c where id =: getid];
                customAttachment.Attachment__c = attachmentResult.getId();
                update customAttachment;
            }
        } catch (Exception e) {
            ApexPages.AddMessages(e);
            return null;
        }
        return new PageReference(retst);
    }
    public PageReference back() {
        return new PageReference(retst);
    }
}

 
Alain CabonAlain Cabon
getid = ApexPages.currentPage().getParameters().get('id');}  // must be resolved so you need to pass the parameter 'id'

ApexPages.currentPage().getParameters().put('parameter', 'value');

ApexPages.currentPage().getParameters().put('id', doc.id);

Not the complete solution that is important for your test.
 
Alain CabonAlain Cabon

PageReference myVfPage = Page.MyVFPName;
Test.setCurrentPage(myVfPage); // Put Id into the current page Parameters
ApexPages.currentPage().getParameters().put('id',doc.id);
UploadAttachmentController controller = new UploadAttachmentController(newApexPages.StandardController(doc));
 
This was selected as the best answer
Ryan GreeneRyan Greene
Thanks Alain
Forgot to add in my VF Page for testing, your suggestions worked perfectly!