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);
}
Related
I am trying to modify data and save changes to my database using EFCore 3.1.
but my modifications are not being saved to the database, so after further investigation I found out that after I pull my entity from the context, its state is DETACHED instead of ATTACHED,
so that's why the changes aren't being saved, because they're not tracked in the first place.
I couldn't figure out why this is happening, I made sure that I did not add AsNoTracking() when getting the entity.
Here are my classes and methods:
public class UserSettingsDataAccess : IUserSettingsDataAccess
private readonly NotificationDBContext _context;
private readonly IReminderDatesDataAccess _reminderDatesDataAccess;
public UserSettingsDataAccess(NotificationDBContext context, IReminderDatesDataAccess reminderDatesDataAccess)
{
_context = context;
_reminderDatesDataAccess = reminderDatesDataAccess;
}
public bool ToggleRemindersForAppointmentAsync(int appointment_id)
{
Appointments appointment = _appointmentDataAccess.GetByIdWithReminders(appointment_id);
if (appointment == null || appointment.Reminders == null)
return bool.Parse(null);
var x = _context.Entry(appointment).State;
appointment.Reminders.IsActive = !appointment.Reminders.IsActive;
var y = _context.Entry(appointment).State;
_context.SaveChanges();
var z = _context.Entry(appointment).State;
return appointment.Reminders.IsActive.Value;
}
//rest of code is omitted for brevity
}
This one uses another method to get the appointment, toggle its reminder , save changes and return the new reminder state. all of x,y,z variables have DETACHED value . when debugging
Here's the second class that contains the method that brings the appointment :
public class AppointmentDataAccess: IAppointmentDataAccess
{
private readonly NotificationDBContext _context;
public ReminderDatesDataAccess(NotificationDBContext context)
{
_context = context;
}
public Appointments GetByIdWithReminders(int appointment_id)
{
return _context.Appointments.Where(a => a.Id == appointment_id && a.DeletedAt == null)
.Include(a=>a.Reminders).FirstOrDefault();
}
}
Startup.cs :
services.AddDbContext<NotificationDBContext>(options => options
.UseSqlServer(Configuration.GetConnectionString("Database"))
, ServiceLifetime.Transient,ServiceLifetime.Transient);
and IUserSettingsDataAccess, IAppointmentDataAccess are just interfaces.
Can anyone point out why this is happening? and how to fix it? it's been driving me crazy for a good couple of hours . TIA!
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);
}
}
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();
I have created a custom visualforce page.
Here in the controller class i want to get a list of all workspaces in a dropdown so that user can make a choice among where to publish the data
Can somebody provide me some guidelines on how to achieve this.
Any help is appreciated.
:)
You need to query the content workspaces and then put them in select option list which can then be referenced in a visualforce page.
Apex Controller:
public Id selectedWorkspaceId { get; set; }
private List<SelectOption> workspaceOptions;
public List<SelectOption> getWorkspaceOptions() {
if(workspaceOptions == null) {
for(ContentWorkSpace workspace : [select id, name from ContentWorkspace]) {
workspaceOptions.addNewSelectOption(
new SelectOption(workspace.id, workspace.name);
}
}
}
return workspaceOptions;
}
Visualforce Page:
<apex:selectList value="{!selectedWorkspaceId}" size="1">
<apex:selectOptions value="{!workspaceOptions}"/>
</apex:selectList>
Documentation:
SelectOption Class
<apex:selectList> component
<apex:selectOptions> Component
ContentWorkSpace object
Below is Java code (from code reciepe) to Query a List of Workspaces in Salesforce CRM Content. Translate below code to apex and it should work.
package com.sforce;
import org.apache.axis.client.Stub;
import com.sforce.soap.enterprise.*;
import com.sforce.soap.enterprise.sobject.*;
public class QueryWorkspace {
/**
* #param args
*/
public static void main(String[] args) {
QueryWorkspace queryWorkspace = new QueryWorkspace();
try {
queryWorkspace.queryAvailableWorkspaces();
} catch (Exception ex) {
ex.printStackTrace(System.err);
}
}
private void queryAvailableWorkspaces() throws Exception {
SforceServiceLocator sforceServiceLocator
= new SforceServiceLocator();
SoapBindingStub binding
= (SoapBindingStub) sforceServiceLocator.getSoap();
// Login
LoginResult lr = binding.login("user#jstest.org",
"password");
binding._setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY,
lr.getServerUrl());
// Create a session header for subsequent calls
_SessionHeader sessionHeader = new _SessionHeader();
sessionHeader.setSessionId(lr.getSessionId());
binding.setHeader(sforceServiceLocator.getServiceName()
.getNamespaceURI(), "SessionHeader",
sessionHeader);
QueryResult query
= binding.query("select Id, Name from"
+ " ContentWorkspace");
SObject[] records = query.getRecords();
if (records != null) {
for (int i = 0; i < records.length; i++) {
ContentWorkspace contentWorkspace =
(ContentWorkspace)records[i];
System.out.println("Workspace Id:"
+ contentWorkspace.getId() + " Name:"
+ contentWorkspace.getName());
}
}
}
}
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.