You need to sign in to do that
Don't have an account?
jaanvivek
Unit Testing for Apex
Please make me correct for writing unit test class for the following Apex class-
public class practiseOneController { public Account getAccount() { Account[] acc= [select id,Name,(select id,firstname,lastname from Contacts limit 5) from Account where id= :System.currentPageReference().getParameters().get('id')]; if(acc.size()>0) { return acc[0]; } else { return null; } } // Test Method for this main class static testMethod void TestpractiseOneController() { practiseOneController testObj= new practiseOneController(); Account testAcc=new Account(); testAcc.Name='testaccount'; insert testAcc; testObj.getAccount(); } }
I tried but not getting to cover
:System.currentPageReference().getParameters().get('id')]; if(acc.size()>0) { return acc[0]; }
In this apex class i am trying to show the accociated contacts with the Account.
Thanks & regards,
JaanVivek
Hi,
Please replace str=testAcc.Id; with testObj.id = testAcc.id; and str=null; with testObj.id = null;
Thanks,
Anoop Asok
All Answers
Hi,
This code is not getting covered since you're trying to extract the id value from the page reference which doesn't exist.
Workaround
-----------------
1. Create a public variable to hold the id value.
2. Write a constructor and set the id value to System.currentPageReference().getParameters().get('id')
3. Update your test method to insert some dummy Account records, since by default during test execution none of the existing data in the env will be visible to the logic.
4. Set the value of the public variable created on step 1 with the id of one of the dummy account and contact records created on step 3.
5. Invoke getAccount() method.
6. delete the dummy account records OR reset id value to null.
7. invoke getAccount() method again.
This will probably give you 100% coverage.
Thanks,
Anoop Asok
Hi,
I have tried as below but still it's lacking to get some data in Account[].
Please suggest in this.
Thanks & regards,
JaanVivek
Hi,
Please replace str=testAcc.Id; with testObj.id = testAcc.id; and str=null; with testObj.id = null;
Thanks,
Anoop Asok