You need to sign in to do that
Don't have an account?
jucuzoglu
System.NullPointerException: Attempt to de-reference a null object
I am attempting to create a unit test for a controller and looking to use the Test.setCurrentPage method.
When I do I am getting the error mentioned above on the last line displayed in the code below:
ID contactRecordID = [Select Id from Contact Where FirstName = 'Mark' AND LastName = 'Smith' Limit 1].Id; PageReference ref = new PageReference('/apex/UpdateContactInformation?id=' + contactRecordID); Test.setCurrentPage(ref);
When I run the following code through the Execute Anonymous I get
ID contactRecordID = [Select Id from Contact Where FirstName = 'Mark' AND LastName = 'Smith' Limit 1].Id; PageReference ref = new PageReference('/apex/UpdateContactInformation?id=' + contactRecordID); System.Debug('********' + ref);
Resulting line in log
11:15:01.074|USER_DEBUG|[3]|DEBUG|********System.PageReference[/apex/UpdateContactInformation?id=003T000000sICrPIAW]
So it looks good (as far as I can tell) in the execute anonymous but when run in the Unit test I am getting the System.NullPointerException: Attempt to de-reference a null object error on the last line.
Your extension, with test method, should probably look like this:
Let me know if that helps you any.
Note that I changed save() to saveRecord(), and you should change it on your page. That avoids a possible conflict with StandardController's save() method on the page.
All Answers
Don't use a Partial Page reference. Instead, do this:
Hi,
When you are running from execute anonymous it is working as your database in having the record mentioned in the query.
But when you run the test methd, the test method treats as if your database is empty. That is why you have to create the dummy records in your test method. Your test method will not commit those records to the database but will use it in current context.
So in your test code what you can do is, instaed of querying the record first create the dummy record as follows.
Contact objContact = new Contact();
objContact.FirstName = 'Mark';'
objContact.LastName = 'Smith';
insert objContact;
Then you can use
PageReference ref = new PageReference('/apex/UpdateContactInformation>id=' + objContact.Id);
Test.setCurrentPage(ref);
And that should work fine!!
Here is how I encorporated your code:
Now I am getting the same error: System.NullPointerException: Attempt to de-reference a null object
On this line:
Any ideas what I may be missing?
Ok it appears the problem is with a different line then what is being reported.
I think the issue has to do with the fact that I am not really testing a controller, but instead trying to test a controller extension. So my syntax is off, but not sure how. Here is the code of the controller I am trying to test.
Please let me know if I need to adjust how I am declaring the controller in order to make this work.
Thank You for the assistance
Your extension, with test method, should probably look like this:
Let me know if that helps you any.
Note that I changed save() to saveRecord(), and you should change it on your page. That avoids a possible conflict with StandardController's save() method on the page.
Worked like a charm! I now have 100% coverage.
I tried this approach but still getting the same null pointer error in my test class. Any help will be appreciated.
Controller:
public class leadController {
Public Id leadId;
Lead mylead;
Public Id recTypeId;
public Lead getlead() {
if(mylead == null) mylead = new Lead();
return mylead;
}
public String AccountName{get; set;}
public String ContactFirstName{get; set;}
public String ContactLastName{get; set;}
public leadController(ApexPages.StandardController controller) {
leadId = ApexPages.currentPage().getParameters().get('id');
}
public pagereference saveRecord(){
Database.LeadConvert lc = new database.LeadConvert();
lc.setLeadId(leadId);
lc.setDoNotCreateOpportunity(true);
Account account = new Account(name = AccountName,
Lynx_ID__c = mylead.LYNX_Id__c,
Account_SMP_Id__c = mylead.SMP_Id__c,
ID_1__c = myLead.LYNX_Id__c);
insert account;
lc.setAccountId(account.id);
Contact contact = new Contact(LastName = ContactLastName,
FirstName = ContactFirstName,
Lynx_ID__c = mylead.LYNX_Id__c,
SMP_ID__c = mylead.SMP_Id__c,
AccountID = account.id);
insert contact;
lc.setContactId(contact.id);
LeadStatus convertStatus = [SELECT Id,
MasterLabel
FROM LeadStatus
WHERE IsConverted=true LIMIT 1];
lc.setConvertedStatus(convertStatus.MasterLabel);
Database.LeadConvertResult lcr = Database.convertLead(lc);
System.assert(lcr.isSuccess());
if(lcr.isSuccess()){
Id AcctId = lcr.getAccountId();
Id ContactId = lcr.getContactId();
//Associate Customer Plans to new Account created on lead conversion
List<RecordType> recType = new List<RecordType>();
recType = [Select Id, Name, SobjectType from RecordType];
for(Integer j=0;j<recType.size();j++)
{
if(recType[j].Name == 'AgHorizon Record Type for Account')
{
recTypeId = recType[j].Id;
System.debug('***********Record type1*************' +recType[j].Id);
System.debug('***********Record type2*************' +recTypeId);
}
}
List<Quota_and_Targets__c> custPlan = new List<Quota_and_Targets__c>();
custPlan =[select id,
Lead__c,
RecordTypeId,
RecordType.Name
from Quota_and_Targets__c
where Lead__c =:leadId];
If(custPlan.size()>0)
for(Integer i=0;i<custPlan.size();i++)
{
custPlan[i].Account__c=AcctId;
custPlan[i].RecordTypeId=recTypeId;
System.debug('***********Record type3*************' + custPlan[i].RecordTypeId);
update custPlan;
}
PageReference Page = new PageReference('https://cs8.salesforce.com/'+AcctId);
Page.setRedirect(true);
return Page;
}
else{
return null;
}
}
}
Test class:
@isTest
private class leadControllerTest {
static testMethod void leadControllerTest() {
// PageReference pref;
Lead lead = new Lead();
lead.LastName = 'New AgH Lead';
lead.Phone = '123456789';
lead.Company = 'Cargill';
lead.Status = 'Open';
lead.Lynx_ID__c = '123450';
lead.SMP_ID__c = '80';
insert lead;
// Convert the Lead
Database.LeadConvert lc = new database.LeadConvert();
lc.setLeadId(lead.id);
lc.setDoNotCreateOpportunity(true);
/* Account acct = new Account();
acct.Name = 'Test Account';
acct.Lynx_ID__c = lead.Lynx_ID__c;
acct.Account_SMP_Id__c = lead.SMP_ID__c;
acct.ID_1__c = lead.Lynx_ID__c;
insert acct;*/
Account account = new Account(name = 'AccountName',
Lynx_ID__c = lead.LYNX_Id__c,
Account_SMP_Id__c = lead.SMP_Id__c,
ID_1__c = Lead.LYNX_Id__c);
insert account;
lc.setAccountId(account.id);
Contact contact = new Contact(LastName = 'ContactLastName',
FirstName = 'ContactFirstName',
Lynx_ID__c = lead.LYNX_Id__c,
SMP_ID__c = lead.SMP_Id__c,
AccountID = account.id);
insert contact;
lc.setContactId(contact.id);
LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus
where IsConverted=true limit 1];
lc.setConvertedStatus(convertStatus.MasterLabel);
Database.LeadConvertResult lcr = Database.convertLead(lc);
System.assert(lcr.isSuccess());
if(lcr.isSuccess()){
Id AcctId = lcr.getAccountId();
Id ContactId = lcr.getContactId();
}
// Lead test_lead = new lead(LastName = 'TestLead');
ApexPages.StandardController SC = new ApexPages.StandardController(lead);
Test.startTest();
leadController controller = new leadController(SC);
ApexPages.PageReference returnPage = controller.saveRecord(); -- ----Attempt to dereference a null object------
Test.stopTest();
// System.assertEquals(test_lead.Status__c,'Open');
System.assertEquals(returnPage.getUrl(),'https://cs8.salesforce.com/'+account.Id);
}
}
controller
public without sharing class PartnerSSOPortalController {
String role ='Partner';
String accessLevel ='Edit';
private static Visible_to_Partners__c[] m_oppMembers = new List<Visible_to_Partners__c> ();
List<Opportunity> oppList = new List<Opportunity>();
Integer i=0;
String userids=UserInfo.getUserId();
//added by ankita for Search criteria
public String acc {get;set;}
public String opp {get;set;}
// public Opportunity opp {get{opp = new Opportunity(); return opp;}set;}
public String stage {get; set;}
public List<SelectOption> stages;
public Boolean error {get; private set;}
public String errorMessage {get; private set;}
public String severity {get; private set;}
public String message {get; private set;}
Id accId;
/******************* Newly Added************************/
Integer queryLimit;
Integer offset;
// for active and deactive page naviagator
public Boolean firstOff{set;get;} // previous part
public Boolean lastOff{set;get;} // next part
public String limits{set;get;}
public Integer pageNumber{set;get;}
Integer listSize;
/******************Newly Added********************/
public PartnerSSOPortalController(){
/**************Newly Added**********************
firstOff = false;
queryLimit = 10;
offset = 0;
limits = '10';
pageNumber = 1;
list<Opportunity> res = new list<Opportunity>();
res=[select id from Opportunity limit 50000 ];
// fill size of all contact
//listSize = res.size();//Integer.valueOf(res.get('cnt'));
// initialy check page more then 1 or not
//if(listSize > queryLimit)
lastOff = true;
//else lastOff = false;
*******************Newly Added*****************/
//total_size = [select count() from Opportunity ]; //set the total size in the constructor
//selectedPage='0';
accId = [select Contact.accountId from User where id = :UserInfo.getUserId()].Contact.AccountId;
//system.debug('***Account of User:'+accId+':'+UserInfo.getUserId());
message = 'If you cannot find the opportunity you are looking for below, please use the search form above.';
oppList = [select Id, Name, stagename,CloseDate,ownerid, Account.name ,Account.BillingCountry
from Opportunity
where sold_to_Partner__c = :accId
and Isclosed=false
and Id not in (select OpportunityId from OpportunityTeamMember where userid=:userids )
order by Name limit 200];
showList();
}
public PageReference search(){
String query = 'select Id, Name, stagename,CloseDate,ownerid, Account.name,Account.BillingCountry from Opportunity where Isclosed=false and Sold_To_Partner__c = \''+accId+'\' and Id not in (select OpportunityId from OpportunityTeamMember where userid=\''+userids+'\' ) ';
if(acc != null && acc.length() >= 3)
{
String accName = '%'+acc+'%';
query += ' and account.name like \''+accName+'\'';
}
if(stage != null && !stage.equals(''))
{
query += ' and stagename = \''+stage+'\'';
}
if(opp != null && opp.length() >= 3)
{
String oppName = '%'+opp+'%';
query += ' and name like \''+oppName+'\'';
}
query += ' limit 50 ';
//system.debug('***Query:'+query);
oppList = Database.Query(query+' LIMIT '+queryLimit+' OFFSET '+offset);
/*if(stage == null || stage.equals('')){
oppList = [select Id, Name, stagename,CloseDate,ownerid, Account.name
from Opportunity
where sold_to_Partner__c = :accId
and account.name like :accName
and Isclosed=false
and Id not in (select OpportunityId from OpportunityTeamMember where userid=:userids )
order by Name limit 1000];
}else{
oppList = [select Id, Name, stagename,CloseDate,ownerid, Account.name
from Opportunity
where sold_to_Partner__c = :accId
and stagename = :stage
and account.name like :accName
and Isclosed=false
and Id not in (select OpportunityId from OpportunityTeamMember where userid=:userids )
order by Name limit 1000];
}*/
//if(oppList.size() > 0){
showList();
//}
return null;
}
public List<SelectOption> getStages(){
List<SelectOption> stages = new List<SelectOption>();
Schema.DescribeFieldResult F = Opportunity.StageName.getDescribe();
List<Schema.PicklistEntry> P = F.getPicklistValues();
stages.add(new SelectOption('','All'));
for(Schema.PickListEntry ple : P){
stages.add(new SelectOption(ple.getValue(), ple.getLabel()));
}
return stages;
}
public List<OpportunityWrapper> ow {get;set;}
public PageReference back() {
List<OpportunityWrapper> selectedopp = new List<OpportunityWrapper>();
PageReference pr = System.Page.PartnerSSO_OpportunityList;
pr.setRedirect(true);
return pr;
}
public void showList() {
//get{
error = false;
errorMessage = '';
selectedopp.clear();
//oppList.clear();
if(ow != null){
ow.clear();
}else{
ow = new List<OpportunityWrapper>();
}
// Id accId = [select Contact.accountId from User where id = :UserInfo.getUserId()].Contact.AccountId;
//oppList = [select Id, Name, stagename,CloseDate,ownerid from Opportunity where sold_to_Partner__c = :accId and Isclosed=false and Id not in (select Opportunity_Name__c from Visible_to_Partners__c where PartnerName__c=:userids and role__c='Partner') order by Name];
// oppList = [select Id, Name, stagename,CloseDate,ownerid from Opportunity where sold_to_Partner__c = :accId and Isclosed=false and Id not in (select OpportunityId from OpportunityTeamMember where userid=:userids ) order by Name];
if(!oppList.isEmpty()) {
for(Opportunity c : oppList){
OpportunityWrapper cw = new OpportunityWrapper(c);
ow.add(cw);
}
}
// return ow;
// }
//set;
}
public PageReference Updateopp() {
selectedopp.clear();
List<Visible_to_Partners__c> vpc = new List<Visible_to_Partners__c>();
for (OpportunityWrapper cw : ow) {
if (cw.checked){
try{
vpc = [select id from Visible_to_Partners__c where PartnerName__c=:userids and Opportunity_Name__c=:cw.ops.id];
}catch(Exception e){
System.debug('***********'+e);
}
selectedopp.add(new OpportunityWrapper(cw.ops));
Visible_to_Partners__c tmSTP = new Visible_to_Partners__c(PartnerName__c=userids,Opportunity_Name__c=cw.ops.id,role__c=role,Opportunity_Access__c=accessLevel,ownerid=cw.ops.ownerid);
m_oppMembers.add(tmSTP);
System.debug('***********'+cw.ops.id);
}
}
if (selectedopp.size() > 0 && selectedopp.size() < 6 ) {
try{
if(vpc.size()>0){
delete vpc;
}
insert m_oppMembers;
}catch(DMLException e){
System.debug('Exception in adding user to sales team: ' + e.getMessage());
error = true;
errorMessage = e.getDMLMessage(0); //+ opp.Name ;
if(errorMessage.equalsIgnoreCase('operation performed with inactive user')){
errorMessage = 'You cannot be added to the Sales team of one (or more) opportunity below. Please try updating one opportunity at a time. If the problem persists, please contact ISR.';
}
severity = 'error';
selectedopp.clear();
return null;
}
PageReference pr = new PageReference('/apex/PartnerSSOoppselected');
return pr;
}else {
/* ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Please select atleast one and maximum 5');
ApexPages.addMessage(myMsg);*/
error = true;
errorMessage = 'Please select atleast one and maximum 5';
severity = 'error';
selectedopp.clear();
return null;
}
return null;
}
public List<OpportunityWrapper> selectedopp {
get {
if (selectedopp == null)
{
selectedopp = new List<OpportunityWrapper>();
}
return selectedopp ;
}
set;
}
/*****************newly Added***************/
//public List<Contact> getRecords(){
//return (List<Contact>)database.query(queryString+' LIMIT '+queryLimit+' OFFSET '+offset);
// }
// navigate on next page
public void next(){
offset += queryLimit;
if(offset+queryLimit >= listSize) lastOff = false;
firstOff = true;
pageNumber++;
}
// navigate on previous page
public void previous(){
if(offset-queryLimit <= 0){
offset = 0;
firstOff = false;
}
else offset -= queryLimit;
lastOff = true;
pageNumber--;
}
// switch on first page
public void first(){
offset = 0;
firstOff = false;
lastOff = true;
pageNumber = 1;
}
// switch on last page
public void last(){
// set page number of and offset
if(Math.Mod(listSize,queryLimit) == 0){
offset = listSize-queryLimit;
pageNumber = listSize/queryLimit;
}
else{
offset = (listSize/queryLimit)*queryLimit;
pageNumber = (listSize/queryLimit)+1;
}
lastOff = false;
firstOff = true;
}
// for record limits
public List<SelectOption> getItems(){
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('10','10'));
options.add(new SelectOption('20','20'));
options.add(new SelectOption('50','50'));
options.add(new SelectOption('100','100'));
return options;
}
// change query limit
public void changeLimit(){
// set query limit
queryLimit = Integer.valueOf(limits);
offset = 0;
firstOff = false;
// initialy check page more then 1 or not
if(listSize > queryLimit) lastOff = true;
else lastOff = false;
// set page number
pageNumber = 1;
}
// for show current record numbers
public String getRecordInfo(){
integer lastLimit; //System.NullPointerException: Attempt to de-reference a null object
if(offset+queryLimit > listSize) lastLimit = listSize;
else lastLimit = offset+queryLimit;
return (offset+1) + ' - ' + lastLimit + ' of '+listSize;
}
// return total page number
public Integer getTotalPage(){
if(Math.Mod(listSize,queryLimit) == 0) return listSize/queryLimit;
else return (listSize/queryLimit)+1;
}
// for direct page switching
public void pageNavigation(){
/* if user enter more then number ot total page number than
set the value last page number in PageNumber. */
if(Math.Mod(listSize,queryLimit) == 0 && pageNumber > listSize/queryLimit)
pageNumber = listSize/queryLimit;
else if(pageNumber > (listSize/queryLimit)+1)
pageNumber = (listSize/queryLimit)+1;
// set offset according to pageNumber
if((pageNumber-1)*queryLimit < 0) offset = 0;
else offset = (pageNumber-1)*queryLimit;
/* if pageNumber is 1 than deactive previous navigator
else if pageNumber is o tha set the value of pageNumber is 1
else if pageNumber is more than 1 active next navigator
*/
if(pageNumber == 1) firstOff = false;
else if(pageNumber == 0) pageNumber = 1;
else if(pageNumber > 1) firstOff = true;
// user enter last number of pagenumber than deactive next navigator
if(Math.Mod(listSize,queryLimit) == 0){
if(pageNumber == listSize/queryLimit) lastOff = false;
else lastOff = true;
}
else{
if(pageNumber == (listSize/queryLimit)+1) lastOff = false;
else lastOff = true;
}
}
/***************Newly Added************************/
}