Writing the test class for an Extension in Apex

When we need to extend the functionality of the a Visualforce page the option that we reach out to is Extension in Apex.

Extension are super duper useful in extending the capabilities of a Visualforce.

If the ask from business is to fetch a single record and display the fields we reach out to Standard Controllers.

Also, standard controller has access to 9 methods that we can straight off use without worrying about anything else.

Now what if we have to add a custom method on top of it?

That’s when extensions will come into picture.

But the catch is how do we write the test class for Extensions?

Extensions will have one argument constructor and it becomes tricky.

This is how we write the test class for extensions.

Account testAccount = new Account(Name='Test Company Name123');
insert testAccount;

ApexPages.StandardController sc = new ApexPages.StandardController(testAccount);
newAccountPlan testAccPlan = new newAccountPlan(sc);

// AccountPlan is the name of the Visualforce page
PageReference pageRef = Page.AccountWizardPage;
// We will be passing the Id in the URL so am gonna pass it here
pageRef.getParameters().put('id', String.valueOf(testAccount.Id));
Test.setCurrentPage(pageRef);
Test class code for an Extension

Hope this helps!