You need to sign in to do that
Don't have an account?
Ronaldo Costa
Retrieve Related Object Fields
Hello,
I have successfuly imeplemented the code below for a custom object, however I can not find any test methods examples over the boards for the same need.
Can anybody please help me write a simple test method for the following class?
public with sharing class RelatedController { private ApexPages.StandardController stdCtrl; public RelatedController(ApexPages.StandardController std) { stdCtrl=std; } public void AccountPopulated() { Contact cont=(Contact) stdCtrl.getRecord(); cont.Account=[select AccountNumber, Site from Account where id=:cont.AccountId]; } }
Original post at BobBuzzard blog
Thanks!!!
Ronaldo.
All Answers
something like:
PageReference pr = new PageReference(some_input_probably_controller_or_object);
Test.setCurrentPage(pr);
and you call the AccountPopulated() with something like:
pr.AccountPopulated() or
some_input_probably_controller_or_object.AccountPopulated()
Thanks a lot!
I managed to get 100% coverage, however there is one failure.
System.QueryException: List has no rows for assignment SObject
It points to:
Any ideas please? I am new to apex, but I believe this is because I did not set any dummy ID at the test code?
Thanks,
Ronaldo.
Hi,
I have given answer below,
But I have doubt in the below lines. You can't access the contact fields without querying, But you try to get Account Id from the Contact Record. First you need to do query on Contact and get the AccountId. Have you excecuted your VF page.
Contact cont=(Contact) stdCtrl.getRecord();
cont.Account=[select AccountNumber, Site from Account where id=:cont.AccountId];
To create test class for your class you need to follow the below step :
1. first you need to create an account record.
2. After creating account you need to create a contact record related to the same account as u have created in step 1.
3. At the end you need to create an object of "ApexPages.StandardController" and pass the contact object as a parameter.
@isTest
private class TestRelatedController {
private static testMethod void unitTest() {
Account acc = new Account (
Name = 'test'
);
insert acc;
Contact con = new Contact (
LastName = 'testCon',
AccountId = acc.Id
);
insert con;
ApexPages.StandardController sc = new ApexPages.standardController(con);
RelatedController controller = new RelatedController(sc);
}
}
Let me know if u have any problem on same .And if this post is helpful please give KUDOS by click on start at left.
Thank you guys so much!
The only thing I needed to add at the end was:
Regards,
Ronaldo Costa.