You need to sign in to do that
Don't have an account?
DavidD
How do I unit test VF controller?
HI, I am very new to VF and Apex Classes.
I just created a VF page with a custom controller in Sandbox. Now I need to do unit test before deployment. I have no clue how to write the unit test:
What I built is a search page, user can type in search criteria and then click on search
Here is my Page:
<apex:page Controller="BannerAdsLocalController" id="page1">
<!-- Begin Default Content REMOVE THIS -->
<h1>Search for Banner Ads Local</h1>
<apex:form id="searchForm" >
<apex:outputLabel value="Category:" for="CategorySelected"/>
<apex:selectList id="Category" value="{!Category}" size="1" >
<apex:selectOptions value="{!Categories}" />
</apex:selectList>
<apex:outputLabel value="Postcode:" for="postcode"/>
<input id="postcode" name="postcode" value="{!$CurrentPage.parameters.postcode}" size="15" maxlength="10" />
<apex:outputLabel value="Start date:" for="startDate"/>
<input id="startDate" name="startDate" value="{!$CurrentPage.parameters.startDate}" size="7" maxlength="10" />(yyyy-mm-dd)
<apex:outputLabel value="End date:" for="endDate"/>
<input id="endDate" name="endDate" value="{!$CurrentPage.parameters.endDate}" size="7" maxlength="10" />(yyyy-mm-dd)
<input type="submit" name="search" value="Search" />
<br /><br />
</apex:form>
<apex:pageBlock title="Banner Ads Local Search Results" rendered="{!NOT(ISNULL(Products))}" >
<apex:pageBlockTable value="{!Products}" var="product">
<apex:column value="{!product.PricebookEntry.Name}"/>
<apex:column value="{!product.ListPrice}"/>
<apex:column headerValue="Opportunity Name" rendered="{!NOT(ISNULL(product))}" >
<apex:outputLink value="/{!product.Opportunity.id}">
{!product.Opportunity.Name}
</apex:outputLink>
</apex:column>
<apex:column value="{!product.Opportunity.StageName}"/>
<apex:column value="{!product.Opportunity.Campaign_Start_Date__c}"/>
<apex:column value="{!product.Opportunity.Campaign_End_Date__c}"/>
</apex:pageBlockTable>
</apex:pageBlock>
<!-- End Default Content REMOVE THIS -->
</apex:page>
Here is my controller:
public class BannerAdsLocalController {
Transient List<OpportunityLineItem> Products;
Transient String Category = null;
Transient String postcode = null;
Transient Date startDate = null;
Transient Date endDate = null;
Transient String s_start = null;
Transient String s_end = null;
public List<SelectOption> getCategories()
{
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('','All categories'));
Schema.DescribeFieldResult categoryField = Schema.sObjectType.Product2.fields.Categories__c;
Schema.PicklistEntry [] values = categoryField.getPickListValues();
for(Schema.PicklistEntry val : values)
{
options.add(new SelectOption(val.getValue(), val.getLabel()));
}
return options;
}
public Date getStartDate()
{
return startDate;
}
public Date getEndDate()
{
return endDate;
}
public String getCategory()
{
return Category;
}
public void setCategory(String Category) {
this.Category = Category;
}
public List<OpportunityLineItem> getProducts()
{
s_start = ApexPages.currentPage().getParameters().get('startDate');
s_end = ApexPages.currentPage().getParameters().get('endDate');
postcode = ApexPages.currentPage().getParameters().get('postcode');
//dynamic SOQL, SOSL and dynamic DML are currently in pilot, and not enabled for all organizations. If you need them
//for your application and are interested in the pilot program, contact your salesforce.com representative.
//so, we have to do the 6 combinnations:
//Error: Compile Error: Dynamic Apex not allowed in this organization, so we have to do the following combinations:
//Products = Database.query( conditions + order_by );
if (s_start != null && s_start<>'' && s_end != null && s_end <>'' && (Category=='' || Category == null) && (postcode ==null || postcode==''))
{
//Date Range only:
startDate = Date.valueOf(s_start);
endDate = Date.valueOf(s_end);
Products = [SELECT Opportunity.Id, Opportunity.Name,Opportunity.StageName,Opportunity.Payment_Stage__c,
Opportunity.Amount,Opportunity.Campaign_Start_Date__c, Opportunity.Campaign_End_Date__c,
PricebookEntry.Name, PricebookEntry.ProductCode,PricebookEntry.Product2.Postcode__c,
Quantity, TotalPrice, UnitPrice, ListPrice, Price_Ex_GST__c, Total_Ex_GST__c, ServiceDate,
End_Date__c , Description
FROM OpportunityLineItem
WHERE Opportunity.RecordTypeId= '012R00000008dGY'
AND
(
(Opportunity.Campaign_End_Date__c >= :startDate and Opportunity.Campaign_End_Date__c <= :endDate ) OR
(Opportunity.Campaign_Start_Date__c >= :startDate and Opportunity.Campaign_Start_Date__c <= :endDate ) OR
(Opportunity.Campaign_End_Date__c >= :endDate and Opportunity.Campaign_End_Date__c <= :startDate ) OR
(Opportunity.Campaign_Start_Date__c >= :endDate and Opportunity.Campaign_Start_Date__c <= :startDate )
)
ORDER BY Opportunity.Campaign_End_Date__c,Opportunity.Name,ListPrice DESC
];
}
else if ((s_start == null || s_start =='') && (s_end == null || s_end=='') && (Category !='' && Category != null) && (postcode == null || postcode == ''))
{
//only category selected:
Products = [SELECT Opportunity.Id, Opportunity.Name,Opportunity.StageName,Opportunity.Payment_Stage__c,
Opportunity.Amount,Opportunity.Campaign_Start_Date__c, Opportunity.Campaign_End_Date__c,
PricebookEntry.Name, PricebookEntry.ProductCode,PricebookEntry.Product2.Postcode__c,
Quantity, TotalPrice, UnitPrice, ListPrice, Price_Ex_GST__c, Total_Ex_GST__c, ServiceDate,
End_Date__c , Description
FROM OpportunityLineItem
WHERE Opportunity.RecordTypeId= '012R00000008dGY'
AND PricebookEntry.Product2.Categories__c = :Category
ORDER BY Opportunity.Campaign_End_Date__c,Opportunity.Name,ListPrice DESC
];
}
else
{
....
}
return Products;
}
}
Can someone give me some hints please?
Any feedback much appriciated!
Regards,
David
I just created a VF page with a custom controller in Sandbox. Now I need to do unit test before deployment. I have no clue how to write the unit test:
What I built is a search page, user can type in search criteria and then click on search
Here is my Page:
<apex:page Controller="BannerAdsLocalController" id="page1">
<!-- Begin Default Content REMOVE THIS -->
<h1>Search for Banner Ads Local</h1>
<apex:form id="searchForm" >
<apex:outputLabel value="Category:" for="CategorySelected"/>
<apex:selectList id="Category" value="{!Category}" size="1" >
<apex:selectOptions value="{!Categories}" />
</apex:selectList>
<apex:outputLabel value="Postcode:" for="postcode"/>
<input id="postcode" name="postcode" value="{!$CurrentPage.parameters.postcode}" size="15" maxlength="10" />
<apex:outputLabel value="Start date:" for="startDate"/>
<input id="startDate" name="startDate" value="{!$CurrentPage.parameters.startDate}" size="7" maxlength="10" />(yyyy-mm-dd)
<apex:outputLabel value="End date:" for="endDate"/>
<input id="endDate" name="endDate" value="{!$CurrentPage.parameters.endDate}" size="7" maxlength="10" />(yyyy-mm-dd)
<input type="submit" name="search" value="Search" />
<br /><br />
</apex:form>
<apex:pageBlock title="Banner Ads Local Search Results" rendered="{!NOT(ISNULL(Products))}" >
<apex:pageBlockTable value="{!Products}" var="product">
<apex:column value="{!product.PricebookEntry.Name}"/>
<apex:column value="{!product.ListPrice}"/>
<apex:column headerValue="Opportunity Name" rendered="{!NOT(ISNULL(product))}" >
<apex:outputLink value="/{!product.Opportunity.id}">
{!product.Opportunity.Name}
</apex:outputLink>
</apex:column>
<apex:column value="{!product.Opportunity.StageName}"/>
<apex:column value="{!product.Opportunity.Campaign_Start_Date__c}"/>
<apex:column value="{!product.Opportunity.Campaign_End_Date__c}"/>
</apex:pageBlockTable>
</apex:pageBlock>
<!-- End Default Content REMOVE THIS -->
</apex:page>
Here is my controller:
public class BannerAdsLocalController {
Transient List<OpportunityLineItem> Products;
Transient String Category = null;
Transient String postcode = null;
Transient Date startDate = null;
Transient Date endDate = null;
Transient String s_start = null;
Transient String s_end = null;
public List<SelectOption> getCategories()
{
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('','All categories'));
Schema.DescribeFieldResult categoryField = Schema.sObjectType.Product2.fields.Categories__c;
Schema.PicklistEntry [] values = categoryField.getPickListValues();
for(Schema.PicklistEntry val : values)
{
options.add(new SelectOption(val.getValue(), val.getLabel()));
}
return options;
}
public Date getStartDate()
{
return startDate;
}
public Date getEndDate()
{
return endDate;
}
public String getCategory()
{
return Category;
}
public void setCategory(String Category) {
this.Category = Category;
}
public List<OpportunityLineItem> getProducts()
{
s_start = ApexPages.currentPage().getParameters().get('startDate');
s_end = ApexPages.currentPage().getParameters().get('endDate');
postcode = ApexPages.currentPage().getParameters().get('postcode');
//dynamic SOQL, SOSL and dynamic DML are currently in pilot, and not enabled for all organizations. If you need them
//for your application and are interested in the pilot program, contact your salesforce.com representative.
//so, we have to do the 6 combinnations:
//Error: Compile Error: Dynamic Apex not allowed in this organization, so we have to do the following combinations:
//Products = Database.query( conditions + order_by );
if (s_start != null && s_start<>'' && s_end != null && s_end <>'' && (Category=='' || Category == null) && (postcode ==null || postcode==''))
{
//Date Range only:
startDate = Date.valueOf(s_start);
endDate = Date.valueOf(s_end);
Products = [SELECT Opportunity.Id, Opportunity.Name,Opportunity.StageName,Opportunity.Payment_Stage__c,
Opportunity.Amount,Opportunity.Campaign_Start_Date__c, Opportunity.Campaign_End_Date__c,
PricebookEntry.Name, PricebookEntry.ProductCode,PricebookEntry.Product2.Postcode__c,
Quantity, TotalPrice, UnitPrice, ListPrice, Price_Ex_GST__c, Total_Ex_GST__c, ServiceDate,
End_Date__c , Description
FROM OpportunityLineItem
WHERE Opportunity.RecordTypeId= '012R00000008dGY'
AND
(
(Opportunity.Campaign_End_Date__c >= :startDate and Opportunity.Campaign_End_Date__c <= :endDate ) OR
(Opportunity.Campaign_Start_Date__c >= :startDate and Opportunity.Campaign_Start_Date__c <= :endDate ) OR
(Opportunity.Campaign_End_Date__c >= :endDate and Opportunity.Campaign_End_Date__c <= :startDate ) OR
(Opportunity.Campaign_Start_Date__c >= :endDate and Opportunity.Campaign_Start_Date__c <= :startDate )
)
ORDER BY Opportunity.Campaign_End_Date__c,Opportunity.Name,ListPrice DESC
];
}
else if ((s_start == null || s_start =='') && (s_end == null || s_end=='') && (Category !='' && Category != null) && (postcode == null || postcode == ''))
{
//only category selected:
Products = [SELECT Opportunity.Id, Opportunity.Name,Opportunity.StageName,Opportunity.Payment_Stage__c,
Opportunity.Amount,Opportunity.Campaign_Start_Date__c, Opportunity.Campaign_End_Date__c,
PricebookEntry.Name, PricebookEntry.ProductCode,PricebookEntry.Product2.Postcode__c,
Quantity, TotalPrice, UnitPrice, ListPrice, Price_Ex_GST__c, Total_Ex_GST__c, ServiceDate,
End_Date__c , Description
FROM OpportunityLineItem
WHERE Opportunity.RecordTypeId= '012R00000008dGY'
AND PricebookEntry.Product2.Categories__c = :Category
ORDER BY Opportunity.Campaign_End_Date__c,Opportunity.Name,ListPrice DESC
];
}
else
{
....
}
return Products;
}
}
Can someone give me some hints please?
Any feedback much appriciated!
Regards,
David
Thank you so much for your help.
I just figured out how to test VF controller. here is one of my test methods:
---------------------------------------------------------------------------
static testMethod void testGetProductsByPostcode()
{
System.Debug('Debugging...');
System.Debug('Unit Test: Banner Ads Local Controller');
PageReference opptyPage = new PageReference('/apex/BannerAdsLocal?postcode=2000');
Test.setCurrentPage(opptyPage);
BannerAdsLocalController Ctrl = new BannerAdsLocalController();
Ctrl.getCategories();
Ctrl.getProducts();
}
-----------------------------------------------------------------------------
Hope it helps the newbies
Message Edited by DavidD on 08-19-2008 07:33 PM
All Answers
Thank you so much for your help.
I just figured out how to test VF controller. here is one of my test methods:
---------------------------------------------------------------------------
static testMethod void testGetProductsByPostcode()
{
System.Debug('Debugging...');
System.Debug('Unit Test: Banner Ads Local Controller');
PageReference opptyPage = new PageReference('/apex/BannerAdsLocal?postcode=2000');
Test.setCurrentPage(opptyPage);
BannerAdsLocalController Ctrl = new BannerAdsLocalController();
Ctrl.getCategories();
Ctrl.getProducts();
}
-----------------------------------------------------------------------------
Hope it helps the newbies
Message Edited by DavidD on 08-19-2008 07:33 PM
Message Edited by jlo on 08-19-2008 11:34 PM
you can help from this code-
@istest(seeAllData = true)
class TestClass
{
static testmethod void test()
{
Profile p = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
User u1 = new User();
u1.Email = 'email1@email.com';
u1.Alias = 'Alias2';
u1.TimeZoneSidKey = 'America/New_York';
u1.LocaleSidKey = 'ca';
u1.EmailEncodingKey = 'UTF-8';
u1.ProfileId = p.id;
u1.LanguageLocaleKey = 'en_US';
u1.FirstName = 'firstname1';
u1.LastName = 'lastname1';
u1.username= 'username1@first.com';
insert u1;
ContentVersion cv = new ContentVersion();
cv.ContentUrl = 'www.gmail.com';
cv.Title = 'Title Test';
insert cv;
ApexPages.currentPage().getParameters().put('Id',cv.Id);
ContentDataController cdc = new ContentDataController();
}
}