How to create code coverage for my Apex Class - salesforce

Here is the class I managed to create, not sure where to start with code coverage as this is my first apex class, or doing anything with salesforce.
Can someone point me in the right direction. Thanks!
public with sharing class VelocifyAcctStatsController
{
public List<Account> acctstats {get;set;}
public VelocifyAcctStatsController()
{
acctstats = [select MVA_Type__c, MVA_Name__c, MVA_Is_VIP__c, MVA_Is_Brand_TM__c, MVA_Classification__c, MVA_Classification_Priority__c, Assets_Owned__c, Portfolio_Overview__c, Active_Opportunities__c, X3x3_Research_One__c, X3x3_Research_Two__c, X3x3_Research_Three__c from account WHERE Id = :ApexPages.currentPage().getParameters().get('Id')];
}
}

This should help you get started:
#isTest
public class VelocifyAcctStatsControllerTest {
#isTest
public static void test(){
Account a = new Account(Name = 'Test acct' );
insert a;
ApexPages.currentPage().getParameters().put('Id', a.Id);
VelocifyAcctStatsController v = new VelocifyAcctStatsController();
System.assertEquals(v.acctstats.size(), 1);
}
}

Related

How do i write test class for below apex code

Please help me in writing test class for below apex code,i wrote a test class which shows only 66% coverage,i am looking for 100%
public class PickListHandler {
#AuraEnabled
public static List<String> getLevel1(string strName) {
List<String> tempLst = new List<String>
for(AggregateResult ar : [select Level_1__c,COUNT(id) from Case_Type_Data__c group by Level_1__c])
{
tempLst.add('Level 1 data is'+ar.get('Level_1__c'));
return tempLst;
}
}
}
Here is test class
#isTest
public class testGetLevel1 {
static testMethod void testGetLevel1() {
List<String> s = PickListHandler.getLevel1('test');
//System.assert(....);
}
}
You need need to create test data for the object Case_Type_Data__c. If you don't create data, the logic inside for loop will not execute.

Objectify Ref<> with #Load is not working with ofy().load().group()

I have a problem Ref<> usage with #Load. Basically I made a copy paste from Objectify website to test #Load annotation with Load Groups.
#Entity
public static class Thing {
public static class Partial {}
public static class Everything extends Partial {}
public static class Stopper {}
#Id Long id;
#Load(Partial.class) Ref<Other> withPartial;
#Load(Everything.class) Ref<Other> withEveryhthing;
#Load(unless=Stopper.class) Ref<Other> unlessStopper;
public Ref<Other> getWithPartial() {
return withPartial;
}
public void setWithPartial(Ref<Other> withPartial) {
this.withPartial = withPartial;
}
public Ref<Other> getWithEveryhthing() {
return withEveryhthing;
}
public void setWithEveryhthing(Ref<Other> withEveryhthing) {
this.withEveryhthing = withEveryhthing;
}
public Ref<Other> getUnlessStopper() {
return unlessStopper;
}
public void setUnlessStopper(Ref<Other> unlessStopper) {
this.unlessStopper = unlessStopper;
}
}
Then I wrote the following code.
Other other = new Other();
Key<Other> otherKey = ofy().save().entity(other).now();
Thing thing = new Thing();
thing.setWithPartial(Ref.create(otherKey));
Key<Thing> thingKey = ofy().save().entity(thing).now();
Thing t = ofy().load().key(thingKey).now();
System.out.println("Is loaded: " + t.getWithPartial().isLoaded());
Without writing ofy().load().group(Partial.class).key(thingKey).now(); other entity still loads into session. However in documentation it needs group class to be loaded.
The isLoaded() method tests whether the entity is in the session cache. Since you just save()d the entity, it's already in the session cache.
If you want to test the behavior of load groups, you need to ofy().clear() the cache.

need help on how to achieve 100% in the test class

I have been trying to write test class for 100% coverage. I have difficulty in understanding how to call the standard controller and call the parameterised constructor also set the page to the current page as the current page.
On the account view page, I have overridden the new button on the related list of a custom object. I am able the use the same class when I edit the record. On both the edit record view page and the new record view page I am able to retrieve the account id. Currently I am able achieve 65% coverage. I am not sure what am I doing wrong. Please help if possible. I have attached the code below.
Thanks
Gayatri
//my Class
public class NewTaxExempt{
public TaxExempt__c obj {get; set;}
public String selectedIso {get;set;}
public List<selectOption> isoCodes {
get {
List<selectOption> options = new List<selectOption>();
for (State__c iso : State__c.getAll().values())
options.add(new SelectOption(iso.State_ISO__c,iso.State_Name__c+' - '+iso.State_ISO__c));
return options;
}
set;
}
// onload standard controller will be called.
public NewTaxExempt(ApexPages.StandardController controller) {
ID idte=controller.getRecord().id;
if(idte==null){
obj=(TaxExempt__c)controller.getRecord();
}
else{
obj= [Select Account__c, Certificate_ID__c, Certificate_Type__c,Description__c, Issuing_Jurisdiction__c,Status__c,Tax_Exempt_Effective_Date__c,Tax_Exempt_Expiration_Date__c from TaxExempt__c where id=:idte];
}
}
//on click on cancel button
public PageReference cancel() {
return new PageReference('/'+obj.account__c);
}
//on click on Save button
public PageReference save() {
obj.Issuing_Jurisdiction__c=selectedIso;
if(obj.id==null){
insert obj;
}
else{
update obj;
}
return new PageReference('/'+obj.account__c);
}
}
//my test class
#isTest
public class NewTaxExemptTest{
public static testMethod void whenIssueJurisdictionIsBlankDefaultValueIsSet(){
try{
BET_ObjectFactory.generateTaxExemptRequirements();
Account aobj = ( Account)TestFactory.createSObject(new Account(Name='test acc gs250144'),true);
PageReference ref = Page.NewTaxExempt;
Test.setCurrentPage(ref);
TaxExempt__c obj=new TaxExempt__c();
obj.account__c=aobj.Id;
obj.Issuing_Jurisdiction__c='RI';
ApexPages.StandardController sc = new ApexPages.StandardController(obj);
NewTaxExempt ob=new NewTaxExempt(sc);
ob.selectedIso='RI';
ob.obj=obj;
ob.save();
System.assertEquals(obj.Issuing_Jurisdiction__c,null);
List<State__c> stList=new List<State__c>();
State__c st=new State__c();
st.Name='ST_11009';
st.State_Name__c='Alabama';
st.State_ISO__c='AL';
st.State_Country_Name__c='United States';
st.State_Country_ISO__c='US';
stList.add(st);
State__c st1=new State__c();
st1.Name='ST_11008';
st1.State_Name__c='Alabama';
st1.State_ISO__c='AL';
st1.State_Country_Name__c='United States';
st1.State_Country_ISO__c='US';
stList.add(st1);
State__c st2=new State__c();
st2.Name='ST_11019';
st2.State_Name__c='Alaska';
st2.State_ISO__c='AK';
st2.State_Country_Name__c='United States';
st2.State_Country_ISO__c='US';
stList.add(st2);
State__c st3=new State__c();
st3.Name='ST_12009';
st3.State_Name__c='Arizona';
st3.State_ISO__c='AZ';
st3.State_Country_Name__c='United States';
st3.State_Country_ISO__c='US';
stList.add(st3);
State__c st4=new State__c();
st4.Name='ST_11309';
st4.State_Name__c='Arkansas';
st4.State_ISO__c='AR';
st4.State_Country_Name__c='United States';
st4.State_Country_ISO__c='US';
stList.add(st4);
State__c st5=new State__c();
st5.Name='ST_21009';
st5.State_Name__c='California';
st5.State_ISO__c='CA';
st5.State_Country_Name__c='United States';
st5.State_Country_ISO__c='US';
stList.add(st5);
State__c st6=new State__c();
st6.Name='ST_23';
st6.State_Name__c='California';
st6.State_ISO__c='';
st6.State_Country_Name__c='';
st6.State_Country_ISO__c='';
stList.add(st6);
insert stList;
List<State__c> allStates = [select State_Name__c, State_ISO__c, State_Country_Name__c, State_Country_ISO__c
from State__c
order by State_Name__c];
for(State__c stt : allStates){
if(stt.State_ISO__c == '' || stt.State_ISO__c == null){
ob.isoCodes.add(new SelectOption(stt.State_ISO__c, stt.State_Name__c));
}
else{
ob.isoCodes.add(new SelectOption(stt.State_ISO__c, stt.State_Name__c));
}
}
System.assertNotEquals(ob.isoCodes.size(),0);
}catch(Exception e){
System.debug('Gayatri exception :'+e);
}
}
public static testMethod void whenUserClicksCancel(){
BET_ObjectFactory.generateTaxExemptRequirements();
Account aobj = ( Account)TestFactory.createSObject(new Account(Name='test acc gs250144'),true);
// PageReference ref = new PageReference(pageName)
// ref.getParameters().put('TaxExempt__c',obj.Id);
// Test.setCurrentPage(ref);
PageReference ref = Page.NewTaxExempt;
Test.setCurrentPage(ref);
TaxExempt__c obj=new TaxExempt__c();
ApexPages.StandardController sc = new ApexPages.StandardController(obj);
NewTaxExempt ob=new NewTaxExempt(sc);
ob.cancel();
}
}
it's gonna be much easier if you knew what part of your code is missing in test coverage.
Go to developer console and run your test
on the bottom of the page select test tab
find your test from the right side (with title: Overall code coverage)
double click on your test
uncovered part will be in red. now try to write tests for them.
If you want to cover your class properties all you have to do is this:
#isTest static void myPropertiesTest(){
MyClass obj = new MyClass();
obj.myProperty = SomeValue;
// now assert a function in you class that uses this property.
// an easy and dumb way is to just assert the property.
System.assertEquals(SomeValue, obj.myProperty);
}

how to call methods within a class which is in a controller extension class?

I am trying to write a test class for a controller extension. This controller extension has another class in it . And this class has a few methods.
public class Extension_Account
{
public Extension_Account(ApexPages.StandardController controller)
{
public class Class1
{
public Class1()
{
/ * code here*/
}
public String getMethod()
{
/* code here */
}
}
}
}
How can i access the method getMethod in my test class?
In my test class i am able to access the contructor for Class1 but not sure how to get to the other method
public with sharing class TestExtension_Account
{
static testMethod void TestPrint()
{
Account a = new Account();
//a.Name='Test Account';
a.FirstName='TestFirst Name';
a.LastName='Test Last Name';
a.BillingStreet='Test billing Street';
a.BillingCity='Test Billing City';
a.BillingState='Test Billing State';
a.BillingCountry='Test Billing country';
a.BillingPostalCode='Test PostCode';
insert a;
PageReference pageRef = Page.printaddressaccount;
pageRef .getParameters().put('id',a.id);
Test.setCurrentPageReference(pageRef);
ApexPages.StandardController controller = new ApexPages.StandardController(a);
Extension_Account ae = new Extension_Account(controller);
ae.getClass1();
ae.getMethod()// gives a compiler error Method does not exist or incorrect signature
}
}
If your extension class has a getClass1() method that returns an instance of Class1, then you can access the methods from that instance, e.g. ae.getClass1().getMethod();

Average test coverage across all Apex Classes and Triggers is 0%, at least 75% test coverage is required

here i have apex class and visualfource page in developer edition, while i am uploading package i am getting error like"Average test coverage across all Apex Classes and Triggers is 0%, at least 75% test coverage is required"so kindly let me know the solution if possible define code.
Apex class:
public virtual class SendEmailToFeedback
{
public String items { get; set; }
Opportunity opportunity;
public String subject{ get; set; }
public String body { get; set; }
public String lid { get; set; }
public String response {get; set;}
List<Opportunity> Opp;
private static testMethod void myShareTest(){
}
public PageReference cancel()
{
return null;
}
public List<Opportunity> getOpp()
{
if(Opp== null)
{
lid = System.currentPageReference().getParameters().get('name');
Opp= [Select o.Name,o.Email__c from Opportunity o where o.id =:lid];
}
return Opp;
}
public PageReference send()
{
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
String addresses;
if (Opp[0].Email__c != null)
{
addresses = Opp[0].Email__c;
if (Opp[0].Email__c != null)
{
addresses += ':' + Opp[0].Email__C;
String[] toAddresses = addresses.split(':', 0);
email.setSenderDisplayName('THYLAKSOFT LLC');
email.setSubject(subject);
email.setToAddresses(toAddresses);
email.setPlainTextBody(body + 'Click The Followoing Link http://tefllife.com/studentfeedback.html');
try
{
Messaging.SendEmailResult [] resultMail= Messaging.sendEmail(new
Messaging.SingleEmailMessage[] {email});
if(resultMail[0].isSuccess())
response = 'ok sent!';
else
{
response = resultMail[0].getErrors().get(0).getMessage();
}
}
catch(System.EmailException ex)
{
response = ex.getMessage();
}
}
}
return null;
}
}
Visualforce page:
<apex:page controller="SendEmailToFeedback" id="thePage">
<apex:page
Before you can deploy your code or package it for the Force.com AppExchange, 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully. This is well documented:
Documentation on testing Apex
Wiki article on Apex Test Methods
Presentation: Apex Test Coverage Best Practices
You need to write test methods that cover at least 75% of your code and they need to run successfully. It's as simple as that, and I don't think anyone is going to write your code for you.

Resources