• JoshTonks
  • NEWBIE
  • 155 Points
  • Member since 2016
  • RAM Tracking

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 26
    Questions
  • 18
    Replies
Ive written this controller extension. 

Im attempting to write the test class for it but im not too sure how to write it for the particular class.

This is my class
 
public class CreatePDFAttachment {
    public String Id;
    public String Name;
    public String OrdId;

    public CreatePDFAttachment(ApexPages.StandardController controller) {
    	
    }
    
    Public pageReference attachment(){
    Id=ApexPages.currentPage().getParameters().get('Id');
    Name=ApexPages.currentPage().getParameters().get('Name');
    OrdId=ApexPages.currentPage().getParameters().get('OrdId');
    
    PageReference attachment = Page.InvCreated;
    attachment.getParameters().put('id',Id);
    attachment.getParameters().put('name',Name);
    attachment.getParameters().put('OrdId',OrdId);
    
    //Attachment for Invoice Record
    Attachment e = new Attachment();
    
    //Attachment for Customer Order
    Attachment f = new Attachment();
    Blob body;
    try{
        body = attachment.getContentasPDF();
    }
    catch(Exception t){
        body = Blob.valueOf('Cannot create PDF');
    }

    // Attachment To Invoice__c
    e.body = body;
    e.Name = Name + ' - ' + system.Now();
    e.isPrivate = false;
    e.parentId = Id;
    e.ContentType = 'application/pdf';
    insert e;
    
    // Attachment To Customer_Order__c    
    f.body = body;
    f.Name = Name + ' - ' + system.Now();
    f.isPrivate = false;
    f.parentId = OrdId;
    f.ContentType = 'application/pdf';
    insert f;
    return new PageReference('/' + Id);

    }
}

For the test class how would i get the references which im currently passing as apexpages.get parameters would i need to create the records in the class. This is what im at so far it doesnt fail but it does have 0 coverage> I thought it would have some sort of coverage.

This is my test class
 
@isTest
private class TestCreatePDFAttachment {
    static testMethod void test1()
    {
        String OrdId = 'a2Z5E000000ky1HUAQ';
        Invoice__c Inv = new Invoice__c(Customer_Order__c = OrdId); 
        insert Inv;
        
        Attachment attach=new Attachment();       
        attach.Name='Unit Test Attachment';
        Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
        attach.IsPrivate=false;
        attach.body=bodyBlob;
        attach.parentId=Inv.id;
        insert attach;
        
        List<Attachment> attachments=[select id, name from Attachment where parent.id=:Inv.id];
        System.assertEquals(1, attachments.size());
        
    }
}

Thank you in advance for any assistance.
 
Hi,

Would anybody please be able to give me assistance on this.
Ive written difference test classes before for different things but i dont know how to do this one. It sends a json api call out to an external service
 
public class RAMAssistSetup {
    @InvocableMethod(label='RAM Assist Setup ' description='This sets up ram assist')
    public static void RAMAssistSetup(List<Id> FleetAssist) {
        List<Fleet_Assist__c> RFA =[Select Id from Fleet_Assist__c where id in :FleetAssist ];
        System.enqueueJob(new RestApiCall(FleetAssist));
    }
    public class RestApiCall implements System.Queueable, Database.AllowsCallouts {
        List<Id> RFA = new List<Id>() ; 
        public RestApiCall(List<Id> ids){
            RFA = ids ;
        }
        public void execute(System.QueueableContext ctx) {
            Fleet_Assist__c FA = [Select Id ,Contact_Email__c,Company__c,Contact_Full_Name__c,Company_Name_Text__c,Contact_Telephone__c,fm_Licenses__c,fm_Address__c from Fleet_Assist__c where id = :RFA limit 1] ;
            JSONGenerator gen = JSON.createGenerator(true);    
            gen.writeStartObject();      
            gen.writeStringField('email',FA.Contact_Email__c);
            gen.writeStringField('sfId',FA.Company__c);
            gen.writeStringField('name',FA.Contact_Full_Name__c);
            gen.writeStringField('companyName',FA.Company_Name_Text__c);
            gen.writeStringField('tel',FA.Contact_Telephone__c);
            gen.writeStringField('address',FA.fm_Address__c);
            gen.writeStringField('licenses',FA.fm_Licenses__c);
            gen.writeEndObject();    
            String jsonS = gen.getAsString();
            System.debug('jsonMaterials'+jsonS);

            // Sending the http body with JSON 

            String endpoint = 'https://api.xxxxxxxx.com/xxxxxx';
            HttpRequest req = new HttpRequest();
            req.setEndpoint(endpoint);
            req.setMethod('POST');
            req.setHeader('Content-Type','application/json;charset=UTF-8');
            req.setbody(jsonS);
            Http http = new Http();
            HTTPResponse response = http.send(req);
            // Parse the JSON response
            if (response.getStatusCode() != 200) {
                System.debug('The status code returned was not expected: ' +
                    response.getStatusCode() + ' ' + response.getStatus());
            } else {
                System.debug(response.getBody());
            }
            
         }
    }
}
Im assuming looking at it there are 2 test classes for it one for the top section and then one for the restapicall.

Do i need to write a mock httpcallout method for this and will i need to run a record create testmethod for this so it can find the object

Thanks in advance


 
Hi All,

I am trying insert a parameter into the record save in an apex controller extension.

Any help would be appreciated on this.

This is the controller extension pretty basic at the moment
 
public with sharing class CSATExtension
{    
   ApexPages.StandardController stdCtrl;
   // extension constructor
   public CSATExtension(ApexPages.StandardController std)
   {
      stdCtrl=std;
   }

   public PageReference save()
   {
      stdCtrl.save();
      PageReference pr = new PageReference('http://www.ramtracking.com/thankyou');
      pr.setRedirect(true);
      return pr;
   }
}

I have a parameter in the url that comes to this page of PSC.

Do i need to set it like this
 
public integer PSC {get;Set;}

Or would it be with
 
public string PSC = apexpages.currentpage().getparameters().get('PSC');

I cant find a way make an apex form update when saving the existing record stdCtrl.save();

Please if anyone can point me in the right direction
 
What im looking to do is to stamp the record with the url which the apex:form was submitted to. Is this possible using a standard controller with a controller extension?
Hi kind folks,

I am building a quoting system.

I have all the spining up of the information and presenting it to the client thats all working.

what im wanting to do is I currently have a button on each quote option 4 in total which the client clicks. This then wants to update the record with that option being selected so i can set up an internal plain text email alert go from a workflow.

So i have 4 fields Option_1_Selected__c, Option_2_Selected__c, ect.

I have each button as a command button called save1,save2, ect.

I need it to update the corresponding checkbox when clicked so i have written this controller extension but i do not know how to update this one field.
 
public with sharing class UKQuoteExtension {
   
   UKQuote stdCtrl;
   // extension constructor
   public UKQuoteExtension(UKQuote std)
   {
      stdCtrl=std;
   }

   public PageReference save1()
   {
      // stdCtrl.getQuoteOffers();
	  // Option_1_Selected__c = TRUE;
      // Update
      PageReference pr = new PageReference('');
      pr.setRedirect(true);
      return pr;
   }
   public PageReference save2()
   {
      // stdCtrl.getQuoteOffers();
      // Option_2_Selected__c = TRUE;
      // Update
      PageReference pr = new PageReference('');
      pr.setRedirect(true);
      return pr;
   }
   public PageReference save3()
   {
      // stdCtrl.getQuoteOffers();
	  // Option_3_Selected__c = TRUE;
      // Update
      PageReference pr = new PageReference('');
      pr.setRedirect(true);
      return pr;
   }
   public PageReference save4()
   {
      // stdCtrl.getQuoteOffers();
	  // Option_4_Selected__c = TRUE;
      // Update
      PageReference pr = new PageReference('');
      pr.setRedirect(true);
      return pr;
   }
    
}
Im missing something because i need to some how get field from the getQuoteOffers which just returns this record in the controller and then update this field on the record.






 
Hi Guys,

I dont exactly understand what i need to write for a test class for this
 
public PageReference save1(){
		List<RAM_Quote__c> UpdatedQO = new list<RAM_Quote__c>();
		if(!QuoteOffers.isEmpty()){
			for(RAM_Quote__c Id : QuoteOffers){
				UpdatedQO.add(id);
            	Id.Option_1_Selected__c = TRUE;    
				}
           	Update UpdatedQO;
        }
     	PageReference pr = new PageReference('https://google.com');
	 	pr.setRedirect(true);
     	return pr;
	}
Ive done controller extension test classes but it didnt seem to work. Would anybody be able to give me some pointers on this please.

Kind Regards
 
I have an apex class which gets the values of device quantites coming up in the next few days. Im trying to build a display board with visualforce which works.

Im struggling to write a test class which covers the line however the test class is getting a tick in the status in the test logs on the developer console.

This is my class
 
public class LogisticsQuantity {
//Main class
    Date STARTDAY = Date.today();
    Date ENDDAY = STARTDAY.addDays(5);
    public Summary[] Summaries { get; set; }
    public LogisticsQuantity() {
        AggregateResult[] results = [
            SELECT Last_Date_for_Dispatch__c, Count(Id),
            SUM(Hard_Wired_Dash_Camera__c) hard,
            SUM(New_Unit_Qty__c) newUnit,
            SUM(Service_Unit_Qty__c) service
            FROM Unit_Request__c
            WHERE Last_Date_for_Dispatch__c >= :STARTDAY AND Last_Date_for_Dispatch__c < :ENDDAY AND Picked__c = FALSE
            GROUP BY Last_Date_for_Dispatch__c
            ORDER BY Last_Date_for_Dispatch__c ASC NULLS LAST
        ];
        Summaries = new List<Summary>();
        for (AggregateResult ar : results) {
            Summaries.add(new Summary(ar));
        }
    }

    // wrapper class for aggregate data
    public class Summary {
        public decimal NewQuantity { get; set; }
        public decimal SvcQuantity { get; set; }
        public decimal CamQuantity { get; set; }
        public date Name { get; set; }

        public Summary(AggregateResult ar) {
            CamQuantity = (decimal) ar.get('hard');
            NewQuantity = (decimal) ar.get('newUnit');
            SvcQuantity = (decimal) ar.get('service');
            Name = (date) ar.get('Last_Date_for_Dispatch__c');

        }
    }

}

My test class is looking like this im certain i must be missing something from it as im getting code coverage 0
@isTest
public class LogisticsQuantityTest {

    Date TODAY = Date.today();
    
    static testMethod void testLogsticsQuantity() {
    
    Unit_Request__c UR = new Unit_Request__c();
    UR.Date_Of_Job__c = Date.newInstance(2019,12,01);
    UR.Telenor_Elder__c = TRUE;
    UR.Company_Name_Text__c = 'Test Account';
    UR.Contact_Name_Text__c = 'Test Contact';
    UR.Contact_Telephone_Number__c = '01234456789';
    UR.Contact_Email_Address__c = 'test@test.com';
    UR.Unit_Request_to_Case__c = '5008E00000GEaqt';
    UR.LMU_2630_Loom_Standard__c = 1;
    UR.LMU_2630_Loom_Standard__c = 1;
    
    insert UR;
    test.startTest();
}
}

​​​​​​​
Hi,

I need some guidance on to what im not doing correctly.

Im trying to build a custom controller which gets the number of 3 fields on records that are due to be shipped in the next few days grouped by date. 
 
public class LogisticsQuantity {
//your main class
//
    Date STARTDAY = Date.today();
    Date ENDDAY = STARTDAY.addDays(5);

    public Summary[] Summaries { get; set; }

    public LogisticsQuantity() {
        AggregateResult[] results = [
            SELECT Last_Date_for_Dispatch__c, Count(Id),SUM(Hard_Wired_Dash_Camera__c), SUM(New_Unit_Qty__c), SUM(Service_Unit_Qty__c) FROM Unit_Request__c WHERE Last_Date_for_Dispatch__c >= :STARTDAY AND Last_Date_for_Dispatch__c < :ENDDAY 
            GROUP BY Last_Date_for_Dispatch__c 
        ];
        Summaries = new List<Summary>();
        for (AggregateResult ar : results) {
            Summaries.add(new Summary(ar));
        }
    }

    // wrapper class to hold aggregate data
    public class Summary {
        public Integer NewQuantity { get; set; }
        public Integer SvcQuantity { get; set; }
        public Integer CamQuantity { get; set; }
        public String Name { get; set; }

        public Summary(AggregateResult ar) {
            CamQuantity = (Integer) ar.get('Hard_Wired_Dash_Camera__c');
            NewQuantity = (Integer) ar.get('New_Unit_Qty__c');
            SvcQuantity = (Integer) ar.get('Service_Unit_Qty__c');
            Name = (String) ar.get('Last_Date_for_Dispatch__c');
        }
    }

}
I created a visualforce page to test it out on.
<apex:page controller="LogisticsQuantity">
    <apex:form >
        <apex:repeat value="{!Summaries}" var="summary">
            {!summary.Name}: {!summary.NewQuantity} {!summary.SvcQuantity} {!summary.CamQuantity}<br/>
        </apex:repeat>
    </apex:form>
    

</apex:page>
Its blank when there isnt any records that meet any of the criteria but i get Invalid field field_name__c for AggregateResult. Its happening for all 3 fields that im trying to get SUM of.

All these fields are number formula fields with no decimal points. And display as 0 as default value if there is no number in fields it pulls from. Ive never done Aggregate results.


 
Im writing a batch class I have written some previously without issue however when i am writing this this and only 42% coverage. What im trying to do check a box on records that hit the contract end date today which runs a process. It all works just cannot figure out what i need to do get it to test successfully.

This is my Class
 
global class DDBatchUpdate implements Database.Batchable<sObject> {
    Date TODAY = Date.today();
    String DDACTIVE = 'Active';
    global Database.QueryLocator start(Database.BatchableContext BC) { 
        String query = 'SELECT Id FROM DD_Agreement__c WHERE DD_Status__c =: DDACTIVE AND Rolling_End_Date__c = TODAY';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<DD_Agreement__c> DDList) {
        for(DD_Agreement__c DD : DDList)
        {        
            DD.id = DD.id;
            DD.Trigger_Builder__c = TRUE;
        }
        try {
            
            update DDList;
        } catch(Exception e) {
            System.debug(e);
        }
    }   
    global void finish(Database.BatchableContext BC) {
        
  }
}

This is my test class which is only getting 42% coverage It is nearly all the content in global void execute. It is probably something simple im missing.
 
@isTest
private class DDBatchUpdateTest {

static testmethod void test() {

List<DD_Agreement__c> DDList = new List<DD_Agreement__c>(); 
for (Integer i=0;i<200;i++) { 
    DDList.add(new DD_Agreement__c(Trigger_Builder__c=TRUE,DD_Status__c='Active')); 
}
insert DDList;

Test.startTest();
DDBatchUpdate c = new DDBatchUpdate();
Database.executeBatch(c);
Test.stopTest();
    
DD_Agreement__c[] DDUpdatedList = [SELECT Id,Trigger_Builder__c FROM DD_Agreement__c];
System.assert(DDUpdatedList[0].Id != null); 
}
}

Thank you in advance.

 
I have written a Batch Class which is called by a Scheduable class I have written. Im still trying to get my head round tests classes.

I have a test class for the Batch Class. But i dont know how to do write a test class where the schedulable class is calling a Batch Class. This is my Schedule class can someone explain to me what im actually testing for on this one because like I said i fully understand test classes.
 
global class OrderBatchEditScheduler implements Schedulable{
    global void execute(SchedulableContext sc)
    {
       
        OrderDailyBatchEdit b = new OrderDailyBatchEdit();
      
        Database.executebatch(b,200);
    }
   
}

 
I have writen a Batchable class that works in Sandbox. Im trying to write a test class for this and am really struggling to make headway. 

This is my Class 
global class HealthUpdaterBatchable implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) { 
        String query = 'SELECT Id FROM HealthScore__c';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<HealthScore__c> hsList) {
        for(HealthScore__c hs : hsList)
        {        
            hs.id = hs.id;
        }
        try {
        	
            update hsList;
        } catch(Exception e) {
            System.debug(e);
        }
    }   
    global void finish(Database.BatchableContext BC) {
    	
  }
}
This is my test class so far 
private class HealthUpdaterBatchableTest {

static testmethod void test() {

HealthScore__c[] hsList = new List();
for (Integer i=0;i<200;i++) {
HealthScore__c m = new Healthscore__c();
hsList.add(m);
}
insert hsList;

Test.startTest();
HealthUpdaterBatchable c = new HealthUpdaterBatchable();
Database.executeBatch(c);
Test.stopTest();
    
HealthScore__c[] hsUpdatedList = [SELECT Id FROM HealthScore__c];
System.assert(hsUpdatedList[0]);
}
}
Im getting a few errors
  • Expecting < but was ( -Line 6
  •  Invalid type: HealthScore - Line 18
  •  Method does not exist or incorrect signature: void assert(Healthscore) from the type System. - Line 19.
Any advice or assistance is very much appreciated 
 
Hi,

Im having alot of difficulty with this some Apex Code

Im trying to Query Opportunities that are Opp Enquiry Source contains referrals and the event on it is a Sat On Appointment. So i can get a count of them in visualforce.

I know how to display counts in visualforce, I know how to query singular objects for these results but because of the information is on an event and some is on an opportunity I have come to a sticking point.

I thought i might have been able to do this with I was previously advised to do it via this
What.Opp_Enquiry_Source LIKe :IsRef
However this doesnt work and comes up with 

No such column 'Opp_Enquiry_Source__c' on entity 'Name'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names. Is this because of how the What field works on events. That field defiantly exists ive used it previously but its not working

I thought maybe this the following would work 
return [SELECT Count()
            FROM Opportunity o,o.Event e
WHERE o.Opp_Enquiry_Source__c LIKe :IsRef AND e.Sat_On__c = TRUE
Ive tried this both ways so Event e, e.Opportunity o and Opportunity o,o.Event e

I get this as error 

Didn't understand relationship 'e.Opportunity' in field path. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name.

Thank you in advance


 
Im trying to do a count in apex on Events that were marked as cancelled for opportunities that were generated from referrals I know how to build the counts but don't know how or if its possible to combine the two. This is what ive got so far. But im not sure if you can use the WhatId for what im needing.
 
Date THIS_MONTH = System.today().toStartOfMonth();
Date NEXT_MONTH = THIS_MONTH.addMonths(1).addDays(0);
String IsRef = '%'+ 'Referral' +'%';

    public Integer getRefOpps(){
    return [SELECT Count()
            FROM Opportunities
            WHERE Opp_Enquiry_Source__c LIKE IsRef AND CloseDate => THIS_MONTH && CloseDate < NEXT_MONTH AND Stage !=: 'Closed Won' OR Stage !=: 'Completed' 
            ];
     }

    public Integer getCanxRefTask(){
    return [SELECT Count()
            FROM Event
            WHERE AND X1st_Appointment_With_Director__c = TRUE AND ActivityDate >= THIS_MONTH AND ActivityDate < NEXT_MONTH Outcome__c =: 'Cancelled by Them'
            ];
     }

Thank you in advance.
 
Im trying to write a batch apex class that will check a checkbox if it is checked and uncheck them if they are checked. Im stuck on it on a few things I need to make it scheduled and i dont know how to set it so one day it will check them and the next it wont. The last thing is im not sure how to write a test class on this. If anyone can help me with any of this or point me in the right direction i would be grateful.

This is my batch class so far
 
global class FleetAssistUpdaterBatch implements Database.Batchable<sObject>
{
    
   global Database.queryLocator start(Database.BatchableContext ctx )
   {
          
        String str = 'SELECT Id, Trigger_Checkbox__c FROM Fleet_Assist__c WHERE Trigger_Checkbox__c = false';
        
        return Database.getQueryLocator(str);
        
   }
    
    global void execute(Database.BatchableContext ctx, List<Fleet_Assist__c> FAOToProcess)
     {
        
       List<Fleet_Assist__c> FAOList = new List<Fleet_Assist__c>();
       
       for(Fleet_Assist__c FAOObj : FAOToProcess){
               FAOObj.Trigger_Checkbox__c = true;
            FAOList.add(FAOObj);
          }
        
        update FAOList;
     }
   
   global void finish(Database.BatchableContext ctx)
    {
   
      AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
                          TotalJobItems, CreatedBy.Email
                          FROM AsyncApexJob WHERE Id =
                          :ctx.getJobId()];
   // Send an email to the Apex job's submitter notifying of job completion. 
    
   Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
   String[] toAddresses = new String[] {a.CreatedBy.Email};
   mail.setToAddresses(toAddresses);
   mail.setSubject('Apex Sharing Recalculation ' + a.Status);
   mail.setPlainTextBody
   ('The batch Apex job processed ' + a.TotalJobItems +
   ' batches with '+ a.NumberOfErrors + ' failures.');
   Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
           
    }    
}

This is my test class so far
 
@isTest
private class FleetAssistUpdaterBatchTest {
       
   static testMethod void testSchedule() {

        Test.StartTest();
        
        List<Fleet_Assist__c> FAOList = new List<Fleet_Assist__c>();
        
        for(Integer i = 0; i<20; i++){
            Fleet_Assist__c FAOObj = new Fleet_Assist__c();
            FAOObj.Trigger_Checkbox__c = false;
            FAOObj.Company__c = '0010C000002JsnZ';
            FAOObj.Contact__c = '0030C000001EUiL';
            FAOList.add(FAOObj);
        }
        
        insert FAOList;
        
        FleetAssistUpdaterBatch sh1 = new FleetAssistUpdaterBatch();
        String sch = '0 0 23 * * ?'; 
        // system.schedule(, sch, sh1); 
        
        Test.stopTest();
        
   }

    
}

Ive done scheduled apex class before but not with batchable.
 
Ive been writing a class that looks updates a tick box on a custom object. Ive written a test class for it but the the life of me I cannot figure out how to get my test class working.

So this is my Apex Class
global class KPMRefresh implements Schedulable{
  global void execute(SchedulableContext sc){
    List<Metric_Controller__c> lstofMC = [SELECT Id, Refresh_Metrics__c, Which_Month_Boolean__c, Active__c 
                                          FROM Metric_Controller__c 
                                          WHERE Which_Month_Boolean__c = true AND Active__c = true 
                                          LIMIT 200];

    List<Metric_Controller__c> lstofupdatedMC = new list<Metric_Controller__c>();
    if(!lstofMC.isEmpty()){
      for(Metric_Controller__c Id : lstofMC){
        lstofupdatedMC.add(id);
              Id.Refresh_Metrics__c = true;    
        }
             
      UPDATE lstofupdatedMC;
    }

  }
}
This is my test class.
@isTest
private class KPMRefreshTest {
  @testSetup
    static void setup(){
        List<Metric_Controller__c> lstofMC = new List<Metric_Controller__c>();
        for(Integer i = 1; i <= 200; i++){
            Metric_Controller__c Id = new Metric_Controller__c(Refresh_Metrics__c = false);
          lstofMC.add(id);
      }
        Insert lstofMC;   
    }
    
    static testmethod void testKPMRefreshScheduledJob(){
        String sch = '0 5 12 * * ?';
        Test.startTest();
        String jobId = System.schedule('ScheduledApexText', sch, new KPMRefresh());
        
        List<Metric_Controller__c> lstofMC = [SELECT Id, Refresh_Metrics__c FROM Metric_Controller__c WHERE Which_Month_Boolean__c = true AND Active__c = true LIMIT 200];
        
        system.assertEquals(200, lstofMC.size());
        Test.stopTest();   
    }   
}

Ive spent a few hours looking at this and cannot see what im missing. 
 
I was hoping someone could help me. I have a controller extension which saves the record and then redirects the person away from the page. This is for our customers fo a customer feedback this all works for me but I have no idea how i would write a test class for the extension as I have done test classes for other things before but this I cannot get my head around any guidance would be much appreciated. This is my extension below im using www.google.com as a placeholder as I havn't got the page built just yet for the redirect.
 
public with sharing class CSATExtension
{
   ApexPages.StandardController stdCtrl;
   // extension constructor
   public CSATExtension(ApexPages.StandardController std)
   {
      stdCtrl=std;
   }

   public PageReference save()
   {
      stdCtrl.save();
      PageReference pr = new PageReference('http://www.google..com/');
      pr.setRedirect(true);
      return pr;
   }
}

 
Hi,

Im looking to see if there are any tutorials around that shows you how to query a picklist field on an object against a metadata label and output the value of the custom metadata

Example 
Picklist Option
Term: 12 Month

So we would take the 12 Month from the picklist and look for 12 Month in custom metadata term number and then output the value of 12. It didnt used to be an issue however as our company will offer any length of term the formula we were using cannot hold all the term numbers. Which results in us having to update the Formula on a daily basis.

Ive tried to find a tutorial online cannot find anything so if anyone knows a tutorial along those lines I would be very grateful.

Many Thanks In Advance
 
Hi Folk
Im looking for a little help, I was just putting something together for cost saved which we record on individual contacts
List<Contact> CostSaved;
        public List<Contact> getCostSaved() {
               	CostSaved = [SELECT Account_ID__c, SUM(Savings_per_week__c)
                			 FROM Contact, Contact.Account
                			 WHERE Account.Name = 'ram test'
                			 GROUP BY Account_ID__c];
            	return CostSaved;
        }
I am getting Illegal assignment from List<AggregateResult> to List<Contact> im obviously missing something I just cant figure out what.
 
Hi,

I am trying o do a record count on a specific criteria which i have working. However the issue I have is I dont know how to write a test class for it. Ive mainly worked with lists up until now which i can write a test class for. I have attached the apex class below would someone be able to give me some direction on what i need to put in the test class.
 
public class UnitCount {

    public Integer getC2630Counter(){
    	return [SELECT count()
                FROM Unit_Value__c
                WHERE Unit_Type__c =: 'LMU-2630' AND Stock_Status__c =: 'OFFICE' AND Account__c = '0010E00000DHfef' AND Status__c =: 'New Stock'
                ];
	}
}

 
Im trying to create some simple counters. It is going to be more filtered down then this but im getting an error on the 3 and 9 line Variable does not exist: Integer. I think im missing something out because im sure that ive written something similar many moons ago.
public class StatusCheck {
    public Integer getCaseCounter(){
    	return (Integer) = [SELECT count()
                          	FROM Case
                          	WHERE Type =: 'Install'
                          	];
	}
    public Integer getOppCounter(){				
    	return (Integer) = [SELECT count()
                          	FROM Opportunity
                          	WHERE Type =: 'New Business'
                         	];
    						

	}
}

 
Im writing a batch class I have written some previously without issue however when i am writing this this and only 42% coverage. What im trying to do check a box on records that hit the contract end date today which runs a process. It all works just cannot figure out what i need to do get it to test successfully.

This is my Class
 
global class DDBatchUpdate implements Database.Batchable<sObject> {
    Date TODAY = Date.today();
    String DDACTIVE = 'Active';
    global Database.QueryLocator start(Database.BatchableContext BC) { 
        String query = 'SELECT Id FROM DD_Agreement__c WHERE DD_Status__c =: DDACTIVE AND Rolling_End_Date__c = TODAY';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<DD_Agreement__c> DDList) {
        for(DD_Agreement__c DD : DDList)
        {        
            DD.id = DD.id;
            DD.Trigger_Builder__c = TRUE;
        }
        try {
            
            update DDList;
        } catch(Exception e) {
            System.debug(e);
        }
    }   
    global void finish(Database.BatchableContext BC) {
        
  }
}

This is my test class which is only getting 42% coverage It is nearly all the content in global void execute. It is probably something simple im missing.
 
@isTest
private class DDBatchUpdateTest {

static testmethod void test() {

List<DD_Agreement__c> DDList = new List<DD_Agreement__c>(); 
for (Integer i=0;i<200;i++) { 
    DDList.add(new DD_Agreement__c(Trigger_Builder__c=TRUE,DD_Status__c='Active')); 
}
insert DDList;

Test.startTest();
DDBatchUpdate c = new DDBatchUpdate();
Database.executeBatch(c);
Test.stopTest();
    
DD_Agreement__c[] DDUpdatedList = [SELECT Id,Trigger_Builder__c FROM DD_Agreement__c];
System.assert(DDUpdatedList[0].Id != null); 
}
}

Thank you in advance.

 
I have written a Batch Class which is called by a Scheduable class I have written. Im still trying to get my head round tests classes.

I have a test class for the Batch Class. But i dont know how to do write a test class where the schedulable class is calling a Batch Class. This is my Schedule class can someone explain to me what im actually testing for on this one because like I said i fully understand test classes.
 
global class OrderBatchEditScheduler implements Schedulable{
    global void execute(SchedulableContext sc)
    {
       
        OrderDailyBatchEdit b = new OrderDailyBatchEdit();
      
        Database.executebatch(b,200);
    }
   
}

 
I have writen a Batchable class that works in Sandbox. Im trying to write a test class for this and am really struggling to make headway. 

This is my Class 
global class HealthUpdaterBatchable implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) { 
        String query = 'SELECT Id FROM HealthScore__c';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<HealthScore__c> hsList) {
        for(HealthScore__c hs : hsList)
        {        
            hs.id = hs.id;
        }
        try {
        	
            update hsList;
        } catch(Exception e) {
            System.debug(e);
        }
    }   
    global void finish(Database.BatchableContext BC) {
    	
  }
}
This is my test class so far 
private class HealthUpdaterBatchableTest {

static testmethod void test() {

HealthScore__c[] hsList = new List();
for (Integer i=0;i<200;i++) {
HealthScore__c m = new Healthscore__c();
hsList.add(m);
}
insert hsList;

Test.startTest();
HealthUpdaterBatchable c = new HealthUpdaterBatchable();
Database.executeBatch(c);
Test.stopTest();
    
HealthScore__c[] hsUpdatedList = [SELECT Id FROM HealthScore__c];
System.assert(hsUpdatedList[0]);
}
}
Im getting a few errors
  • Expecting < but was ( -Line 6
  •  Invalid type: HealthScore - Line 18
  •  Method does not exist or incorrect signature: void assert(Healthscore) from the type System. - Line 19.
Any advice or assistance is very much appreciated 
 
Im trying to do a count in apex on Events that were marked as cancelled for opportunities that were generated from referrals I know how to build the counts but don't know how or if its possible to combine the two. This is what ive got so far. But im not sure if you can use the WhatId for what im needing.
 
Date THIS_MONTH = System.today().toStartOfMonth();
Date NEXT_MONTH = THIS_MONTH.addMonths(1).addDays(0);
String IsRef = '%'+ 'Referral' +'%';

    public Integer getRefOpps(){
    return [SELECT Count()
            FROM Opportunities
            WHERE Opp_Enquiry_Source__c LIKE IsRef AND CloseDate => THIS_MONTH && CloseDate < NEXT_MONTH AND Stage !=: 'Closed Won' OR Stage !=: 'Completed' 
            ];
     }

    public Integer getCanxRefTask(){
    return [SELECT Count()
            FROM Event
            WHERE AND X1st_Appointment_With_Director__c = TRUE AND ActivityDate >= THIS_MONTH AND ActivityDate < NEXT_MONTH Outcome__c =: 'Cancelled by Them'
            ];
     }

Thank you in advance.
 
I was hoping someone could help me. I have a controller extension which saves the record and then redirects the person away from the page. This is for our customers fo a customer feedback this all works for me but I have no idea how i would write a test class for the extension as I have done test classes for other things before but this I cannot get my head around any guidance would be much appreciated. This is my extension below im using www.google.com as a placeholder as I havn't got the page built just yet for the redirect.
 
public with sharing class CSATExtension
{
   ApexPages.StandardController stdCtrl;
   // extension constructor
   public CSATExtension(ApexPages.StandardController std)
   {
      stdCtrl=std;
   }

   public PageReference save()
   {
      stdCtrl.save();
      PageReference pr = new PageReference('http://www.google..com/');
      pr.setRedirect(true);
      return pr;
   }
}

 
Hi,

Im looking to see if there are any tutorials around that shows you how to query a picklist field on an object against a metadata label and output the value of the custom metadata

Example 
Picklist Option
Term: 12 Month

So we would take the 12 Month from the picklist and look for 12 Month in custom metadata term number and then output the value of 12. It didnt used to be an issue however as our company will offer any length of term the formula we were using cannot hold all the term numbers. Which results in us having to update the Formula on a daily basis.

Ive tried to find a tutorial online cannot find anything so if anyone knows a tutorial along those lines I would be very grateful.

Many Thanks In Advance
 
Hi Folk
Im looking for a little help, I was just putting something together for cost saved which we record on individual contacts
List<Contact> CostSaved;
        public List<Contact> getCostSaved() {
               	CostSaved = [SELECT Account_ID__c, SUM(Savings_per_week__c)
                			 FROM Contact, Contact.Account
                			 WHERE Account.Name = 'ram test'
                			 GROUP BY Account_ID__c];
            	return CostSaved;
        }
I am getting Illegal assignment from List<AggregateResult> to List<Contact> im obviously missing something I just cant figure out what.
 
Hi,

I am trying o do a record count on a specific criteria which i have working. However the issue I have is I dont know how to write a test class for it. Ive mainly worked with lists up until now which i can write a test class for. I have attached the apex class below would someone be able to give me some direction on what i need to put in the test class.
 
public class UnitCount {

    public Integer getC2630Counter(){
    	return [SELECT count()
                FROM Unit_Value__c
                WHERE Unit_Type__c =: 'LMU-2630' AND Stock_Status__c =: 'OFFICE' AND Account__c = '0010E00000DHfef' AND Status__c =: 'New Stock'
                ];
	}
}

 
Im trying to create some simple counters. It is going to be more filtered down then this but im getting an error on the 3 and 9 line Variable does not exist: Integer. I think im missing something out because im sure that ive written something similar many moons ago.
public class StatusCheck {
    public Integer getCaseCounter(){
    	return (Integer) = [SELECT count()
                          	FROM Case
                          	WHERE Type =: 'Install'
                          	];
	}
    public Integer getOppCounter(){				
    	return (Integer) = [SELECT count()
                          	FROM Opportunity
                          	WHERE Type =: 'New Business'
                         	];
    						

	}
}

 
Im still learning and i must be doing something wrong im getting an Illegal assignment from List to List on the following code on line 7. Also on a second note does anyone have a link for any books on apex or courses that cover the list functionality please.
 
public with sharing class monthlylist {
	public list<Opportunity> Monthly;
    Date startOfMonth = Date.today().toStartOfMonth();
	Date startOfNextMonth = startOfMonth.addMonths(1);
    
    public list<Opportunity> Monthly(){
    Monthly = [SELECT Owner.Name, COUNT(id)
               FROM Opportunity
              WHERE StageName = :'Closed Won, Complete' AND CloseDate >= :startOfMonth AND CloseDate < :startOfNextMonth AND UK_Canada__c = 'UK'
              GROUP BY Owner.Name];
    return Monthly;
}
}

 
Im trying to write a test class for the below code. Ive written test classes before for things but for the life of me I cannot figure out how to get this to work with it. I feel like im missing something obvious. My apex class is below. The public list is passing the rest isnt.
public with sharing class CAengineerInvoices {

  List<Service_Booking__c> CAengineerInvoices;
      Service_Booking__c NetTotal;
      Service_Booking__c GrossTotal;
    
    public List <Service_Booking__c> getCAengineerInvoices(){
      CAengineerInvoices = [SELECT   Eng_Qty__c, CA_Gross_Amount__c, CA_Gross_Total_VF__c, Description_Of_Work__c, Description_of_Additional_work__c,Service_Company_Name__c, Company_Name__c, Registration_s__c, Name, Booking_Date_Time__c, CA_Eng_Net_Price__c, KM_Over__c, CA_Tax_Amount__c,Gross_Amount__c, Booking_Date_Time_Fomrula__c
                     FROM Service_Booking__c
                     WHERE Booking_Confirmed__c = True AND Service_Company__c = :ApexPages.currentPage().getParameters().get('Id')];
      return CAengineerInvoices;
    }

	public Service_Booking__c getNetTotal() {
       NetTotal = new Service_Booking__c(CA_Eng_Net_Price__c = 0);
       
       for(Service_Booking__c CAI : getCAengineerInvoices()){
           NetTotal.CA_Eng_Net_Price__c += CAI.CA_Eng_Net_Price__c;
           }
           return NetTotal;
      }


	public Service_Booking__c getGrossTotal() {
       GrossTotal = new Service_Booking__c(CA_Gross_Total_VF__c = 0);
       
       for(Service_Booking__c GT : getCAengineerInvoices()){
           GrossTotal.CA_Gross_Total_VF__c += GT.CA_Gross_Total_VF__c;
           }
           return GrossTotal;
      }
	public Account getAccount() {
        return [SELECT Id, Name FROM Account
                WHERE Id = :ApexPages.currentPage().getParameters().get('Id')];
    }
}

 
Im fairly new to apex im only just getting into it.

I have written the following but Im still trying to get my head round writing a test class and would be grateful for any assistance on doing so. Im sure ill eventually get my head round this.
 
public class CaseCon {
    List<case> CaseCon;
        public List<case> getCaseCon() {
            CaseCon = [SELECT Account.Name, Owner.Name, CaseNumber
                       FROM Case
                       WHERE Urgent__c = :TRUE];
            return CaseCon;
        }
}

 
Hi I was hoping someone would be able to give me a little advice or point me in the right direction if the information is already documented somewhere. Im looking to build some functionality onto an object where the quantity of a quantity field would define the quantity of records to create. Similar to how payment schedule works on products. So if I specified 10 in quantity box it would create 10 related object records.