You need to sign in to do that
Don't have an account?
Nandini
Test class for page reference ?
Hi Team,
How can we write the test class for below class.
Thanks,
sfdc dev.
How can we write the test class for below class.
public with sharing class ControllerCls { public Contact co{get;set;} private final Contact con; private ApexPages.StandardController sc{get;set;} public Opportunity opp = new Opportunity(); public ControllerCls(ApexPages.StandardController sc){ this.sc = sc; con = (Contact)sc.getRecord(); if(con.Name__c != Null){ opp =[select id,name,AccountId from Opportunity where id =: con.Name__c limit 1]; } co = new Contact(); co.AccountId = opp.AccountId; } public PageReference save(){ try{ Database.insert(con); PageReference pr = new PageReference('/'+con.Id); pr.setRedirect(true); return pr; }catch(Exception ex){ ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, ex.getMessage())); return null; } } public PageReference saveNew() { PageReference pr; try{ Database.insert(con); Schema.DescribeSObjectResult describeResult = sc.getRecord().getSObjectType().getDescribe(); pr = new PageReference('/' + describeResult.getKeyPrefix() + '/e'); pr.setRedirect(true); return pr; }catch(Exception e){ ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage())); return null; } } }Please let me know how can we cover 100% code coverage.
Thanks,
sfdc dev.
Try below code you will get 100% code coverage.
You have to set reference of your page in Test Class
Let me know if it's help you.
Did you put the code like above ?. I get the code coverage 100%.
Did you achieve 100% coverage. please let me know if you still face any problem.
Can please share me your code. So I can look into it, help you out.
Please try this code:
@istest
public class TestControllercls {
@istest
static void controller()
{
Account a=new Account();
a.name='new ac';
insert a;
Opportunity op=new Opportunity();
op.name='new op';
op.closedate=date.today();
op.StageName='Prospecting';
op.accountid=a.id;
insert op;
Contact c=new Contact();
c.lastname='new contact';
c.Name__c=op.Id;
c.accountid=a.id;
Test.startTest();
ApexPages.StandardController sc=new ApexPages.StandardController(c);
Controllercls cc=new Controllercls(sc);
cc.save();
Test.stopTest();
}
@istest
static void method2()
{
Account a=new Account();
a.name='new ac';
insert a;
Opportunity op=new Opportunity();
op.name='new op';
op.closedate=date.today();
op.StageName='Prospecting';
op.accountid=a.id;
insert op;
Contact c=new Contact();
c.lastname='new contact';
c.Name__c=op.Id;
c.accountid=a.id;
Test.startTest();
ApexPages.StandardController sc=new ApexPages.StandardController(c);
Controllercls cc=new Controllercls(sc);
cc.saveNew();
Test.stopTest();
}
}
Hope this code will help you. Mark it as best answer if find it helpful.
Thankyou.
Ajay Dubedi