Salesforce coding lessons for the 99%
Finally, Apex tutorials for point-and-click admins! Written by a self-taught Google engineer.
  • Beginner Tutorials
    • Apex
    • Certifications
    • Career Info
    • Technical Architect
    • Visualforce
    • Videos
  • Apex Academy
  • Success Stories
  • About Me
  • Misc
    • Mailbag
    • Challenges
    • Links
    • Login to my Org
Follow @dvdkliuor SUBSCRIBE!

Example: How to write a test class

May 14, 2013

Preface: this post is part of the Write Your First Trigger From Start to Finish series.

Want to push code from sandbox to production? You need to write a test class first!

Salesforce requires at least 75% of your code to be “tested” before deploying to your normal org. They just want to make sure your code doesn’t break the cloud.

So if we wanted to deploy our simple trigger, we’d first need to write test code that would “trigger” our trigger. Start by going here:

Setup >> Develop >> Apex Classes >> New

Now try to guess what this test code is doing. It may seem like a lot, but most of it is just nonsense you can ignore. Remember – focus on the green highlighted lines!

@isTest 
public class TestForceForecasting {
    static testMethod void insertNewUser() {
       
User userToCreate = new User();
// Do you recognize these fields?
userToCreate.FirstName = 'David'; userToCreate.LastName = 'Liu'; userToCreate.Email = 'dvdkliu+sfdc99@gmail.com'; userToCreate.Username = 'sfdc-dreamer@gmail.com'; userToCreate.Alias = 'fatty';
userToCreate.ProfileId = '00ei0000000rTfp';
// Don't worry about these userToCreate.TimeZoneSidKey = 'America/Denver'; userToCreate.LocaleSidKey = 'en_US'; userToCreate.EmailEncodingKey = 'UTF-8'; userToCreate.LanguageLocaleKey = 'en_US';
insert userToCreate;
} }

If you haven’t figured it out already, all this test code does is create a new user in Salesforce. Since our simple trigger executes when a new user is created, we’re testing it!

Now – how does Salesforce know we have 75% test code coverage?

If this test class runs at least 75% of the lines of code in our simple trigger, we can deploy our trigger to production. Since our trigger has only five lines of code, we need to run at least four of them, rounding up. This test will run all five, so we’re in the clear!

Next post: An extended look: How to write a test class

150 Comments
Anonymous
November 30, 2020 @ 10:23 am

Can some one help me to write test class I try but its cover only 48%

@IsTest

public class TestProjectControler
{

public static testmethod void ProjectControler_Test()
{
Account acc = new Account(Name = ‘Test Account1′);
Insert acc;

Project__c proj1 = new Project__c(Account__c = acc.id, Financial_Year__c =’2014-15’);
insert proj1;

Service_Clarity__c serv = new Service_Clarity__c (Project__c = proj1.id, Document_Type__c = ‘MSA’,Documents_Checked__c = ‘Yes’,Service_as_per_CPC__c = ‘Test’,Eligible__c = ‘Yes’,Foreign_Client_Name__c =’Test’,Remarks__c =’Test’);
insert serv;
List projwrapper = new List();
projwrapper = ProjectControler.getprojectserviceclarity(proj1.id);

}
}

Reply
    Anonymous
    November 30, 2020 @ 10:25 am

    Code as below…

    public class ProjectControler {

    @AuraEnabled
    public static List getprojectserviceclarity(Id projectid){
    List projserverlist = new List();
    Set projaccid = new Set ();
    List projlist = new List ();
    Set fyear = new Set();

    projlist = [select id, Account__c,financial_year__c from Project__c where Id =:projectid ];
    for (Project__c pro :projlist )
    {
    projaccid.add(pro.Account__c);
    fyear.add(pro.financial_year__c);

    }

    List sercl = [ select Id, Name,Account__r.Name, Document_Type__c, Documents_checked__c,Financial_Year__c from Service_Clarity__c where Account__r.Id IN :projaccid AND Financial_Year__c IN : fyear ];

    for(Service_Clarity__c sc :sercl)
    {
    ProjectControler.projectserviceclaritywrapper projserwrapper = new ProjectControler.projectserviceclaritywrapper();
    projserwrapper.Name = sc.Name;
    projserwrapper.DocumentType = sc.Document_Type__c;
    projserwrapper.DocumentCheck = sc.Documents_checked__c;
    projserwrapper.Account = sc.Account__r.Name;

    projserverlist.add(projserwrapper);
    }

    return projserverlist;
    }

    public class projectserviceclaritywrapper
    {

    @AuraEnabled public String Name {set; get;}
    @AuraEnabled public String DocumentType { set; get; }
    @AuraEnabled public String DocumentCheck { set; get; }
    @AuraEnabled public String Account { set; get; }
    @AuraEnabled public Id SerId { set; get; }

    }
    }

    Reply
Harish KP
September 16, 2020 @ 11:53 pm

Hi David,

The below test class is failing by some unknown reason.While checking the trigger I can see l.LastName is still in red area. Could you help me on this.
@istest
public class HelloWorldTest {

@istest static void updateLead(){
Lead myLead = new Lead();
myLead.FirstName=’Harish’;
myLead.LastName =’KK’;
myLead.Company =’AAA’;
insert myLead;
myLead.Company =’BBBB’;
myLead.LastName =’KP’;
update myLead;
}
}

Reply
Pierre
November 24, 2018 @ 12:21 pm

Shouldn’t the test class test that the forecast checkbox is selected when appropriate?

Your test class only test that a new lead can be created if I am not mistaken? Is that really all it takes to achieve 75%+ code coverage?

Reply
Mike Davis
October 30, 2018 @ 9:41 am

Hi David. I followed along with the steps here and my test Class was created.

However when I go to Apex Test Execution and run a test on that class-it says (0/1) Test Methods Passed.

What did I input wrong? I copied your code:

@isTest
public class TestForceForecasting {
static testMethod void insertNewUser() {

User userToCreate = new User();

// Do you recognize these fields?
userToCreate.FirstName = ‘David’;
userToCreate.LastName = ‘Liu’;
userToCreate.Email = ‘dvdkliu+sfdc99@gmail.com’;
userToCreate.Username = ‘sfdc-dreamer@gmail.com’;
userToCreate.Alias = ‘fatty’;
userToCreate.ProfileId = ’00ei0000000rTfp’;

// Don’t worry about these
userToCreate.TimeZoneSidKey = ‘America/Denver’;
userToCreate.LocaleSidKey = ‘en_US’;
userToCreate.EmailEncodingKey = ‘UTF-8’;
userToCreate.LanguageLocaleKey = ‘en_US’;

insert userToCreate;
}
}

Reply
    Kelle
    November 7, 2018 @ 5:23 am

    @Mike – one thing that sticks you need to remove the //comments

    Reply
Kevin
April 2, 2018 @ 5:07 pm

Hello David,

Thanks for making this website. It has certainly helped me out. I have a question regarding the following test class that I created for your apex academy tutorial. While the test class is running successfully, it isn’t covering the trigger. Any idea why?

Trigger:

trigger helloWorld on Lead (before update) {
for (Lead led : Trigger.new){
led.FirstName = ‘Hello’;
led.LastName = ‘World’;
}
}

Test Class:

@isTest
public class TesthelloWorld {
static testMethod void tstLed() {
Lead [] ledId = [SELECT Id, FirstName, LastName, Company FROM Lead];
for (Lead lId : ledId){
lId.FirstName = ‘Test’;
lId.LastName = ‘User1’;
lId.Company = ‘ABC Testing Co.’;

update lId;
}
}
}

Thanks in advance

Reply
    David Liu
    April 2, 2018 @ 9:06 pm

    Try using a system debug in there =) Very interesting why it doesn’t work!

    Reply
      Kevin
      April 6, 2018 @ 2:53 pm

      Thanks David! The debug statements helped to narrow down the issue. I completely forgot to create the Lead in the Class before updating it. It is working now and I have 100% code coverage.

      Reply
    Chinmay Abhangrao
    July 5, 2018 @ 10:35 pm

    @istest public class TestClassForHelloworld {

    @istest public static void LeadCreationAndUpdate(){

    Lead abc =new Lead();
    abc.LastName=’chinmay’;
    abc.Company=’dummy pvt ltd’;
    insert abc;

    update abc;
    }

    }

    Reply
Nidhi Soni
October 27, 2017 @ 12:16 pm

Hey David,

Could you please explain me this error!
Operation: Compiling: WarrantySummaryTest.cls
Timestamp: Fri, 27 Oct 2017 15:12:48
Result: [ERROR]: WarrantySummaryTest (ApexClass) was not found on the server.
It’s been a while I practiced apex on plural-sight. I picked up where I left.
How can I fix this ?

Reply
    David Liu
    October 28, 2017 @ 12:08 am

    Looks like your coding editor is out of sync with your org! Or you have the wrong org setup!

    Reply
Harshavardhan
September 3, 2017 @ 2:33 am

HI David

While executing test and deployment to production how does system understand the corresponding test class for particular trigger.
Is there any dependency or reference of this test class for a trigger ForceForecasting.

Reply
    Neevan
    April 23, 2018 @ 12:27 am

    good question David please reply

    Reply
      David Liu
      April 23, 2018 @ 9:54 pm

      Nope, Salesforce just runs every line of code that’s “triggered” from your test class, then calculates coverage from there.

      It has no idea what test class you’re trying to cover!

      It’s very common for a single test class to generate some coverage for many triggers!

      Reply
Barry Denson
June 2, 2017 @ 5:56 am

Hi David

trying to add a trigger to post to chatter when an attachment is added.

trigger NotifyOwner on Attachment (after insert)
{

for (Attachment a: Trigger.new)
{

User u = [SELECT UserType, Name FROM User WHERE Id=:a.CreatedById];

FeedItem post = new FeedItem();

post.ParentID = u.id;
post.Body = ‘Hello ‘+u.name+’ – A file or note was attached to a record you own’;

insert post;

}

}

This is my code, and I have written a test with 100% code coverage but when I add an attachment, nothing gets posted to chatter.

Any suggestions

Reply
    Barry Denson
    June 5, 2017 @ 1:17 am

    Update: Using query builder, select Id from attachment returns no rows, but there are attachments in my org??

    Reply
Anonymous
April 23, 2017 @ 10:29 am

Hi friends,

I have build an app Test class generator, it helps to generate test class in some clicks.
Please have a look.

https://appexchange.salesforce.com/listingDetail?listingId=a0N3A00000EFozgUAD

Thanks…

Reply
Asad
April 13, 2017 @ 10:21 pm

Please cover the test class.
public Id editId {set;get;}
Public Edition_Feature__c ef {get;set;}

public AddNewEditionFeatureExt(ApexPages.StandardController stdController) {
ef = (Edition_Feature__c)stdController.getRecord();
if(ef.Edition__c != null){
editId = [SELECT id, name From Edition__c Where Id=:ef.Edition__c limit 1].Id;
}
else if(ApexPages.currentPage().getParameters().get(‘retURL’) != null ){
String RetURL = ApexPages.currentPage().getParameters().get(‘retURL’);
System.debug(RetURL);
String EditionFeatureId = RetURL.substring(1);
editId = [SELECT id,edition__c,name From Edition_Feature__c Where Id=:EditionFeatureId limit 1].Edition__c;
}

if(editId != null){
ef.Edition__c = editId;
}
}
}

Reply
Asad
April 13, 2017 @ 6:17 am

Please any1 tell how to write a test class for these.
public class AddNewEditionFeatureExt {

public Id editId {set;get;}
Public Edition_Feature__c ef {get;set;}

public AddNewEditionFeatureExt(ApexPages.StandardController stdController) {
ef = (Edition_Feature__c)stdController.getRecord();
if(ef.Edition__c != null){
editId = [SELECT id, name From Edition__c Where Id=:ef.Edition__c limit 1].Id;
}
else if(ApexPages.currentPage().getParameters().get(‘retURL’) != null ){
String RetURL = ApexPages.currentPage().getParameters().get(‘retURL’);
System.debug(RetURL);
String EditionFeatureId = RetURL.substring(1);
editId = [SELECT id,edition__c,name From Edition_Feature__c Where Id=:EditionFeatureId limit 1].Edition__c;
}

if(editId != null){
ef.Edition__c = editId;
}
}
}

Reply
Asad
April 13, 2017 @ 3:35 am

how to write test class for this
public void calcIsueDate()
{
Integer a;
for(a = 0; a < ps.Size(); a++)
{

if(ps[a].Issue_No__c != null){
Printing_Schedule_Date__c psDate = [select Issue_Date__c from Printing_Schedule_Date__c
where Issue_No__c = :ps[a].Issue_No__c and
Product_Type__c = :ps[a].Publishing_Product_Type__c ];

ps[a].Issue_Date__c = psDate.Issue_Date__c;
}
}

Reply
Asad
April 12, 2017 @ 10:41 pm

Please Someone help me in this
My apex class
public class SendEmailTemplate2{

public Opportunity standOpp {get ;set;}
public String validSender = ”; // Public: Required and used in TestCase
public String validCcAddresses = ”; // For Valid ccAddresses
public String validbCcAddresses = ”; // For Valid bccAddresses
public String validSubject = ”;// Public: Required and used in TestCase
public String validBody = ”; // Public: Required and used in TestCase
private String vFlags ; // Selected Items from SelectList
public String cAddresses; // For ccAddresses
public String bcAddresses; // For bccAddresses
public String[] addCcAddresses; // Collecting multiple Addresses
public boolean ccAdd = false; // For Format Validations on ccAddresses
public String[] addbCcAddresses; // Collecting multiple Addresses
public boolean bccAdd = false; // For Format Validations on ccAddresses
public Attachment att {get;set;}
// public String FloorplanFile{get;set;}
// public String TemplateFile {get;set;}
public String subject { get; set;} // Subject of Email
public String body { get; set; } // Body of Email
public String Sender { get; set; } // Sender of Email
public String attachParentId;
public String standOppName;
// public String standOppPdf{get;set;}
public String FinalContract {get;set;}
// public Boolean statusCheck {get;set;}
public Id preview {get;set;}

public String getccAddresses(){ // Sending to ccAddresses
return cAddresses;
}

public void setccAddresses(String cAddresses){ // Setting ccAddresses value to Local Variable
this.cAddresses = cAddresses;
}
public String getbccAddresses(){ // Sending to ccAddresses
return bcAddresses;
}

public void setbccAddresses(String bcAddresses){ // Setting ccAddresses value to Local Variable
this.bcAddresses = bcAddresses;
}
public String getValidSender(){ // Validation for Sender
return validSender;
}
public String getValidCcAddresses(){ // Validation for ccAddresses
return validCcAddresses;
}
public String getValidbCcAddresses(){ // Validation for ccAddresses
return validbCcAddresses;
}

public String getValidSubject(){ // Validation for Subject
return validSubject;
}
public String getValidBody(){ // Validation for Body
return validBody;
}
public String getOutgoingEFlagList(){ // Getting SelectedList Value
return vFlags;
}
public void setOutgoingEFlagList(String vFlag){ // Setting SelectedList Value
this.vFlags = vFlag;
}

// Controller: Contact
ApexPages.StandardController Controller;
// public Document document {get;set;}
public Opportunity sOpp{get;set;}

// Constructor: SendEmail
public SendEmailTemplate2(ApexPages.StandardController stdcontroller){
controller = stdcontroller;
this.standOpp = (Opportunity)controller.getRecord();
FinalContract = ‘Contract.pdf’;
// sOpp = [select name,Name__c,opportunity_owner__r.name,Exhibiting_Account__r.name,Sub_Allocation_Name__r.Event_Show__c,Opportunity_Owner__r.phone,Opportunity_Owner__r.fax,Opportunity_Owner__r.title,Opportunity_Owner__r.email,stand_opportunity_contact__c,Isgeneratecontract__c,Exhibiting_Account__c,Exhibiting_Account__r.phone,Exhibiting_Account__r.fax,Exhibiting_Account__r.website,Exhibiting_Account__r.Billingcountry,Exhibiting_Account__r.Billingstate,Exhibiting_Account__r.Billingcity,Exhibiting_Account__r.Billingstreet, Daily__c,finance__c from Stand_opportunity__c where id=:standopp.id];
List a = [select id, name from attachment where name =: ‘Contract.pdf’ ORDER BY CreatedDate DESC];
if(a.size()>0)
preview = a[0].id;
}

//Method: Send Quotation button
public PageReference send() {
try{
String NameOfSender;
String emailIdofSender;
standopp.isGeneratecontract__c=false;
update standopp;
try{
contact con =[select name,email from contact where id=:standOpp.Stand_Opportunity_Contact__c];
Sender=con.email;
NameOfSender=standopp.owner.name; //opportunity_owner__r
emailIdOfSender=standopp.owner.email; // opportunity_owner__r
}catch(System.queryexception ie){}
// Textbox Fields validations
if(!isValid()){
validSender = ”; // If Sender Field is blank
if(Sender == ”){
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,’Sender Email address must be specified’));
validSender = ‘border-size:2px; border-color:red;border-style:solid;’;
}
// Wrong Pattern of Email Id
if (emailFormatChecker(Sender)) {
validSender = ”; // invalid, show error
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,’Enter correct Email address.’));
validSender = ‘border-size:2px; border-color:red;border-style:solid;’;
}
validccAddresses = ”;// Wrong Pattern of ccAddresses
if ( ccAdd ) {
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,’Enter correct cc Email address.’));
validCcAddresses = ‘border-size:2px; border-color:red;border-style:solid;’;
}
validbccAddresses = ”;// Wrong Pattern of ccAddresses
if ( bccAdd ) {
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,’Enter correct bcc Email address.’));
validbCcAddresses = ‘border-size:2px; border-color:red;border-style:solid;’;
}
validSubject = ”; // If Subject Field is blank
if(Subject == ”) {
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,’Email Subject must be specified’));
validSubject = ‘border-size:2px; border-color:red;border-style:solid;’;
}

system.debug(‘testing…’);
return null; // Return to same page with error message at the top
}

else {
validSender = ”;
validSubject = ”;
validBody = ”;
validCcAddresses = ”;
validbCcAddresses = ”;

List attList = [select id,body,name,ContentType from attachment where parentId =: standOpp.id order By createddate desc limit 1];
if(attList[0] != null){
att = attList[0];
}
//system.debug(‘att is ‘+att);
Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
attach.setContentType(att.contentType);
attach.setFileName(att.Name);
attach.setInline(false);
attach.Body = att.Body;

string docName;

// Define the email
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

if( addbCcAddresses != null ) // If addbccAddresses array have EmailIds
email.setbccAddresses(addbCcAddresses);

if(addCcAddresses!=null)
email.setccAddresses(addCcAddresses);

email.setReplyTo(emailIdofSender); //Specify the address used when the recipients reply to the email.
email.setSenderDisplayName(NameOfSender); //Specify the name used as the display name.
email.setSubject(subject);
String[] toAddresses = new String[] {sender}; // Contact as a Recipient: It is always String[]
email.setToAddresses( toAddresses );

email.setHtmlBody( body );

email.setFileAttachments(new Messaging.EmailFileAttachment[] {attach}); // Attach the uploaded file to the email

// Sends the email
Messaging.SendEmailResult[] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,’The mail is sent successfully’));
PageReference Page = new PageReference(‘/’+standopp.id);
Page.setRedirect(true);
return Page;
}
}
catch(Exception ex) {
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,’Please check your input data and fill it again…’+ex));
return null;
}//End:Try-Catch block
} // End:Send()

// Method: Back to Contact button
public PageReference Back()
{
PageReference CustPage = new PageReference(‘/’+standOpp.id);
CustPage.setRedirect(false);
return CustPage;
}

// Method: Page Validation
public Boolean isValid()
{
ccAdd = false; // Assigning Variable to false for next Round Trip
bccAdd = false;
if( cAddresses != ”) { // Checking if User has given any cc Addresses
addCcAddresses = cAddresses.split(‘,’); // Storing ccAddresses into String[]
for(String ccCheck : addCcAddresses){ // Checking format of ccAddresses one by one
if( emailFormatChecker(ccCheck) )
ccAdd = true;

}
}
if( bcAddresses != ”) { // Checking if User has given any bcc Addresses
addbCcAddresses = bcAddresses.split(‘,’); // Storing bccAddresses into String[]
for(String bccCheck : addbCcAddresses){ // Checking format of bccAddresses one by one
if( emailFormatChecker(bccCheck) )
bccAdd = true;
}
}

// This block is called to validate the data entered by user.
if ( (Sender == ”) || (Subject == ”) || emailFormatChecker(Sender) || ccAdd || bccAdd){
return false;}
else
return true;

}//End:isValid()

//Method: Email Format Checker
public boolean emailFormatChecker(String value){
String emailRegex = ‘([a-zA-Z0-9_\\-\\.]+)@((\\[a-z]{1,3}\\.[a-z]{1,3}\\.[a-z]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})’;
Pattern MyPattern = Pattern.compile(emailRegex);
Matcher MyMatcher = MyPattern.matcher(value); // Instantiate a new Matcher object “MyMatcher”
if(!MyMatcher.matches())
return true;
else
return false;
}
}

My test class
@isTest
private class GenerateContractTest2{

static testMethod void TestGenerateContract2(){

User u = [ select id from user limit 1];

Account acc = new Account();
acc.name=’Account’;
acc.Account_Long_Name__c=’this one account’;
acc.lead_source__c=’Partner’;
//acc.account_type__c=’Agent’;
//acc.Account_Name_Copy__c = ‘gvjg’;
acc.HOTEL_Universe__c=true;
acc.big_5_universe__c = true;
insert acc;

Contact con= new Contact();
con.lastname=’contact’;
con.email=’sony2503@gmail.com’;
con.account=acc;
insert con;

Campaign c = new Campaign();
c.name = ‘campaign’;
//c.active = true;
c.type=’Email’;
insert c;

Stand_allocation__c SA = new Stand_Allocation__c();
SA.name=’test2′;
SA.Allocation_Owning_Account__c = acc.id;
SA.Event_Show__c = c.id;
SA.Square_Metres_Allocated__c = 10;
SA.Stand_Revenue_Allocated__c = 12;
SA.Estimated_Allocation_Fulfilment__c = 10;
Insert SA;

Stand_Sub_Allocation__c SSB = new Stand_Sub_Allocation__c();
SSB.name=’Test3′;
SSB.Event_Show__c = c.id;
SSB.Owning_Stand_Allocation__c = SA.id;
SSB.Sub_Allocation_Owning_Account__c = acc.id;
SSB.Square_Metres_Sub_Allocated__c=10;
SSB.Stand_Revenue_Sub_Allocated__c= 12;
insert SSB;

Account_owner__c owner= new Account_owner__c();
owner.Account__c = acc.id;
owner.Account_Owner__c = u.id;
owner.Stand_Sales_Owner__c=true;
owner.Event__c=’HOTEL’;
owner.name=’test4′;
insert owner;

product2 p = new Product2();
p.name = ‘HOTEL 2011 Blue Shell’;
p.productcode=’6151400′;
p.Family = ‘HOTEL 2011′;
p.rate_price__c = 100.00;

insert p;

Opportunity opp = new Opportunity();
opp.name=’test5’;
opp.type_of_stand__c=p.id;
opp.Exhibiting_Account__c = acc.id;
opp.Sub_Allocation_Name__c = SSB.id;
//opp.Owner__c = owner.id;
opp.Stand_Depth__c =10;
opp.Stand_Width__c = 20;
opp.CloseDate = date.newinstance(2011, 10, 25);
opp.StageName = ‘Booked’;
opp.Cancellation_Fee_Amount__c = 1;
//opp.stand_opportunity_contact__c=con.id;
insert opp;

Contact conbooking = new Contact();
conbooking.lastname=’contact1′;
conbooking.email=’sony@gmail.com’;
conbooking.account=acc;
conbooking.role__c=’Booking Contact’;
insert conbooking;

Contact Financecon= new Contact();
Financecon.lastname=’contact2′;
Financecon.email=’sony253@gmail.com’;
Financecon.account=acc;
Financecon.role__c=’Finance’;
insert Financecon;

Contact Authcon= new Contact();
Authcon.lastname=’contact3′;
Authcon.email=’sony250@gmail.com’;
Authcon.account=acc;
Authcon.role__c=’Head of Dept’;
insert Authcon;

Opportunity sopp = [select name,id from opportunity where id=:opp.id];
String content = ‘this is the file’;
Blob docfile = Blob.valueof(content);
document doc = new document();
doc.name=sopp.name;
doc.body=docfile;
doc.folderId=’005D0000005Vo8w’;
insert doc;

ApexPages.StandardController stdController1 = new ApexPages.StandardController(opp);
GenerateContractController2 GC = new GenerateContractController2(stdcontroller1);
SendEmailTemplate2 SendController = new SendEmailTemplate2(stdcontroller1);

/** SendController.conlst=new contact[]{};
SendController.conlst.add(con);
SendController.getaccounts();
SendController.find_contacts();
SendController.sendemail(); **/
String cnt = ‘this is the file.pdf’;
Blob fileatt = Blob.valueof(cnt);
GC.file=fileatt;
GC.attachment.name=’filename.pdf’;
GC.upload();
GC.cancel();
SendController.sender=’sony2503@gmail.com’;
String cc=’sony2503@gmail.com’;
string b=’sony2503@gmail.com’;
SendController.cAddresses=’sony2503@gmail.com’;
SendController.bcAddresses=’pmathur@gmail.com’;
Sendcontroller.getccAddresses();
SendController.setccAddresses(cc);
SendController.setOutgoingEFlagList(‘message’);
Sendcontroller.getbccAddresses();
SendController.setbccAddresses(b);
SendController.getValidSender();
SendController.getValidCcAddresses();
Sendcontroller.getValidbCcAddresses();
SendController.getValidSubject();
Sendcontroller.getValidBody();
SendController.getOutgoingEFlagList();
test.startTest();
// Sendcontroller.send();
PageReference retPageRef = SendController.send();
//Sendcontroller.back();
test.stopTest();
System.assertEquals(null, retPageRef, ‘PageReference returned should be null’);
System.assertEquals(true, ApexPages.hasMessages(ApexPages.Severity.INFO), ‘Should have at some INFO messages’);
System.assertEquals(‘The mail is sent successfully’, ApexPages.getMessages().get(0).getSummary(), ‘Wrong info message’);

}
}
My code coverage is 74% I need 100% Please help me in this.

Reply
    David Liu
    April 12, 2017 @ 10:51 pm

    That’s a lot of code!!!!!

    Reply
      Asad
      April 12, 2017 @ 11:53 pm

      please help me in this

      Reply
      Asad
      April 12, 2017 @ 11:58 pm

      just help to covered atleast 75%. ASAP

      Reply
      Asad
      April 13, 2017 @ 1:10 am

      Hi David
      Only I need to cover this part in test class
      Sender=con.email;
      NameOfSender=standopp.owner.name; //opportunity_owner__r
      emailIdOfSender=standopp.owner.email; // opportunity_owner__r
      Can U Help In This ASAP!
      Please.

      Reply
Martina Ompusunggu
February 28, 2017 @ 1:13 am

I don’t see any changes after write these codes

Reply
TARUN C NAIDU
February 9, 2017 @ 9:24 am

Hi David ,

How to write a test class for this :

public class FindCaseProducts {
private List caseProductList;
public Id caseId {get; set;}

public FindCaseProducts() {
caseId = NULL;
}

public List getCaseProduct() {
caseProductList = [Select c.Product__c, c.Quantity__c, c.Product__r.Name From Case_Product__c c Where c.Case__c =: caseId LIMIT 100];

return caseProductList;
}
}

Reply
Nidhu
August 30, 2016 @ 7:01 pm

Hi David.. when we create a test class and run, how does it identify which is the trigger it has to test.Where do we associate a test class and the trigger intended to be tested. Probably I missed to see the association somewhere..Could you please help clear this doubt?

Reply
    David Liu
    August 30, 2016 @ 7:20 pm

    There is no association at all =) All triggers that are possibly affected are evaluated!

    We cover this A LOT in Apex Academy #1 if you’re curious!

    Reply
      Nidhu
      August 31, 2016 @ 11:10 am

      Hi David…Thanks a lot for the reply. It helps clear the doubt.
      I am a diligent follower of your Apex academy courses. I am at loss of words to thank you enough for such great and structured course and the great content of sfdc99. Thanks again.

      Reply
        David Liu
        August 31, 2016 @ 11:30 pm

        My pleasure Nidhu =) Happy to help! That’s my life’s calling!

        Reply
kushh
August 30, 2016 @ 10:10 am

hiii .. david i am new to salesforce

my question is that …
we want that whever a new contact is insert the email should be different everytime means it should not alllow duplicate email . for that i have used this trigger but it is incorrect could u suggest me right code.

“trigger ct3 on Contact (before insert,before update) {
list cont=[select id,email from contact where id in :trigger.old];

contact b=[select id,email from contact where id =: cont];
for(contact c:trigger.new){
if(c.email!=null || b.email!=null){
if(c.email==b.email){
c.adderror(‘u can not add duplicate email,becus this email is exist in contacts ‘);
}
}
}
}” please suggest me right code!!!

Reply
    pranav
    September 30, 2016 @ 3:59 am

    trigger ct3 on Contact (before insert,before update) {
    list con=new list([select id,email from contact]);
    for(contact c:trigger.new){
    for(Contact cc: con){
    if(c.email!=null){
    if(c.email== cc.email){
    c.adderror(‘u can not add duplicate email,becus this email is exist in contacts’);
    }
    }
    }
    }
    }

    Reply
Noor
August 5, 2016 @ 3:53 am

Hi David
@isTest
public class TestForceForecasting {
static testMethod void insertNewUser() {

User userToCreate = new User();

// Do you recognize these fields?
userToCreate.FirstName = ‘David’;
userToCreate.LastName = ‘Liu’;
userToCreate.Email = ‘dvdkliu+sfdc99@gmail.com’;
userToCreate.Username = ‘sfdc-dreamer@gmail.com’;
userToCreate.Alias = ‘fatty’;
userToCreate.ProfileId = ’00ei0000000rTfp’;

// Don’t worry about these
userToCreate.TimeZoneSidKey = ‘America/Denver’;
userToCreate.LocaleSidKey = ‘en_US’;
userToCreate.EmailEncodingKey = ‘UTF-8’;
userToCreate.LanguageLocaleKey = ‘en_US’;

insert userToCreate;
}
}

User userToCreate = new User(); is it a Sobject or custom object . can u explain this line of code in test class.
it is inbuilt like Account obj or what?

Reply
    David Liu
    August 5, 2016 @ 11:42 am

    User is a standard SObject =)

    Reply
    Devraj Chaudhary
    June 1, 2021 @ 4:19 am

    User is a standard object and we are creating new record for User object.

    Reply
Anonymous
August 5, 2016 @ 3:47 am

User userToCreate = new User();
I dint understand this line .Is this a Standard Object or Custom object in the test class. were all the data store which is static

Reply
sam
August 2, 2016 @ 2:02 pm

i have tried your code but when i tried your test class it is giving a error.

15:59:06:009 FATAL_ERROR System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []

Reply
    David Liu
    August 2, 2016 @ 5:06 pm

    Try to guess what you’re getting this error! What do you think? =)

    Reply
Troy Coffelt
July 20, 2016 @ 5:37 pm

I was hired on at a large company as an “Entry Level Developer” after telling them I had zero developer experience but wanted to go that route since I had obtained my Advanced Admin cert. I decided to stay after work 2 hours 2 days a week and go through your guide (I imagine I’ll be lost fairly soon lol). I have just started so I can’t say anything for or against sfdc99 however, after reading the last three posts I wrote my first trigger (to make an account field populate a specific value upon a new account being created) and it felt like Christmas when it actually worked. lol I have a feeling this is going to be fun!

Reply
    David Liu
    July 21, 2016 @ 1:03 pm

    Very proud of you Troy!!!

    Keep it up you’ll be surprised how quickly you can learn!

    David

    Reply
Meghna
February 1, 2016 @ 2:52 am

Hi David

I am having following wrapper class :
public class AEXP_ICON_Submit_ResponseWrapper{
public String icon_case_id{get;set;}
public String status_message{get;set;}
public String status_code{get;set;}
public List error_messages{get;set;}

public AEXP_ICON_Submit_ResponseWrapper(){
error_messages = new List();
}

public class ErrorMessages{
public String ElementLabel{get;set;}

public ErrorMessages(){
}
}

}

I have written test class for the same but unable to cover last three lines of code.
Please help me with the same. Please find the test class below :
@isTest
private class Test_AEXP_ICON_Submit_ResponseWrapper {
static testMethod void TestData(){
Test.startTest();
AEXP_ICON_Submit_ResponseWrapper resWrapper=new AEXP_ICON_Submit_ResponseWrapper();
resWrapper.icon_case_id =’1234′;
resWrapper.status_message =’status_message’;
resWrapper.status_code =’AB123′;
Test.stopTest();
}
}

Reply
    David Liu
    February 1, 2016 @ 8:25 pm

    Too much code to debug, try the official dev forums or hopefully someone else here can help out!

    Reply
Pawan Gautam
January 12, 2016 @ 11:23 pm

Hi David
i’m new to salesforce..could you please explain how to solve these

• When an account phone number is changed then copy the phone number from Account to all its related contact records.
• When a new Contact is created then Contact phone number should be same as that of its associated Account.
• Send Email to all the contacts stating that their Phone Number has been updated

• Create a Boolean field “Primary” on Line Item Object, When a new Line Item is created for an Invoice then set the Primary = true only if [Unit Price* Unit Sold > Unit Price* Unit Sold] of any of the existing Line Item related to that invoice.
• When the line Item is Updated/Deleted then also recalculation for Primary Line Item should happen.

Reply
    David Liu
    January 13, 2016 @ 8:22 pm

    Most of this can be done without code!

    For the rest, I recommend the developer forums =)

    Reply
    Venu
    May 23, 2016 @ 1:31 pm

    Hi Pawan, we can achieve these through process builder or work flows. vaddellavenu@yahoo.com is my mail id. Please let me know if you need any help.

    Reply
Karl
November 25, 2015 @ 7:38 pm

Hi David,

I am really new about Apex and I tried to recreate your code to create new Opportunity upon creating new account but the code is not working.

here is the code:

trigger NewOpp on Account (before insert) {
for (Account acc : Trigger.new) {
Opportunity opp = new Opportunity();
opp.Name = ‘New Opportunity’;
opp.CloseDate = Date.today();
opp.StageName = ‘Prospecting’;
opp.AccountId = acc.Id;

insert opp;
}
}

Reply
    David Liu
    November 25, 2015 @ 10:02 pm

    Gotta give more information than that!

    What’s the error message, what do you expect to happen, and what is actually happening?

    Good luck!
    David

    Reply
    David Liu
    November 25, 2015 @ 10:02 pm

    Actually you know what – you should be using an “after insert” trigger instead =)

    Reply
Abhishek Kumar
September 17, 2015 @ 8:32 pm

Apex Test Result Detail

Time Started 9/17/2015 8:30 PM
Class TestForceForecasting
Method Name insertNewUser
Pass/Fail Fail
Error Message System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []
Stack Trace Class.TestForceForecasting.insertNewUser: line 21, column 1

I am using my Profile id but for some reason it is throwing the same error as above.

Can you Help?

Thank you

Reply
    David Liu
    September 20, 2015 @ 12:28 am

    Quadruple check it’s the right ID

    Reply
Sfdotcom
September 3, 2015 @ 11:00 pm

Hi David,

I need test class for below case standard controller extnsion. Kindly help me.

public with sharing class CaseController{
public Id caseId {get;set;}
Case casePage;
public CaseController(ApexPages.StandardController controller) {
caseId = ApexPages.CurrentPage().getParameters().get(‘id’);

}

public PageReference redirectRecordType(){
Case cs = [select id, recordTypeId from case where id =: caseId];
//PageReference pf = new PageReference();
if(cs.recordTypeId ==’012J0XXXXXXXXXX’){
return new PageReference (‘/apex/VFPAGE1?id=’+cs.Id);
}
if(cs.recordTypeId == ‘012JYYYYYYYYYY’){
return new PageReference (‘/apex/VFPAGE2?id=’+cs.Id);
}
else{

return new PageReference (‘/’+cs.Id+’/e?retURL=%2F’+cs.ID+’&nooverride=1’);
}
}

}

Reply
    David Liu
    September 5, 2015 @ 9:09 pm

    Can’t write code for you sorry!

    Try writing it first then posting about it.

    Reply
soma
August 10, 2015 @ 10:08 am

David
In the test code i have error in the line userToCreate.ProfileId = ‘00590000002VTKN’;
as you auggested to take first 15 character from ord id the last 3 character i added myself but still it fails and says
Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []
please help me to fix the issue.
thanks
soma

Reply
    Pedro
    September 3, 2015 @ 12:59 am

    Your ProfileID=’00590000002VTKN’ does not looks like a ProfileID but an UserId, ProfileId starts with 00e

    Reply
      soma
      November 12, 2015 @ 5:31 pm

      Hi Pedrog
      Thank you for your reply, at last I wrote successful test trigger :)

      Reply
soma
August 10, 2015 @ 9:46 am

David
The below test code fail in the line userToCreate.ProfileId = ‘00590000002VTKN’;
am not sure from where i should take this profile id , could you please explain what is this profile id

@isTest
public class TestForceForecasting {
static testMethod void insertNewUser() {

User userToCreate = new User();

// Do you recognize these fields?
userToCreate.FirstName = ‘soma’;
userToCreate.LastName = ‘s’;
userToCreate.Email = ‘soma@@gmail.com’;
userToCreate.Username = ‘sfdc@gmail.com;
userToCreate.Alias = ‘fatty’;
userToCreate.ProfileId = ‘00590000002VTKN’;

userToCreate.TimeZoneSidKey = ‘America/Denver’;
userToCreate.LocaleSidKey = ‘en_US’;
userToCreate.EmailEncodingKey = ‘UTF-8’;
userToCreate.LanguageLocaleKey = ‘en_US’;

insert userToCreate;
}
}

thanks
soma

Reply
Anthony Foster
July 16, 2015 @ 4:22 pm

I successfully created my first trigger on insert of a new user (and test class) by adapting this tutorial and included a welcome Chatter post for the new user. Thanks so much David for this great resource.

Reply
    David Liu
    July 16, 2015 @ 4:29 pm

    Well done well done sir!

    Reply
psingh
May 9, 2015 @ 10:50 am

good example anyone can easily learn through this

Reply
    Anonymous
    June 10, 2015 @ 7:06 am

    Yest these tuts are always great. It’s just disappointing that there is so much material on triggers and test, and all of them are on the insert. I’ve spent hours looking for a decemnt tut on update including testing, and nothing.

    Reply
David Le Puil
April 12, 2015 @ 11:47 am

Hi David.
Thx for your tutorial, it helped me a lot.

But I still have problem withle test class.

My code (trigger) is like that.

trigger Updatelookup on Event (before insert, before update){
for (event u : Trigger.new){
u.lookup_contact__c = u.WhoId;
u.Subject = u.Nom_formate__c + u.Raison_visite_formate__c;
}
}

It’s a very simple code that make 2 actions.

The first action take the information in the WhoId field (Event) and put it in my custom lookup field “lookup_contact__c” in event each time a new event is created or updated.

After that, the event subject is populated from 2 fields “u.Nom_formate__c + u.Raison_visite_formate__c;”

In the sandbox, the code works well but has a Code coverage of 0% 0/2. It’s normal because I don’t have any test class.

I tried to understand how works the coding for test but … exemple doesn’t help me a lot.

Do you have any idea ?

Reply
Raj Jain
March 18, 2015 @ 12:10 am

Hi,

Is it possible for users to unsubscribe email notification for specific SARs

Reply
Fadhlie Ikram
March 12, 2015 @ 10:17 pm

Hi David,

When we run the created create contact test class, does contact actually get created?

Thank you.

Reply
    David Liu
    March 12, 2015 @ 10:17 pm

    Nope!

    Reply
sameer khanwalkar
February 10, 2015 @ 9:42 am

Hello David,

Thanks for your tutorial I have started reading. As per you mentioned I have created my first trigger and test class but am unable to find how to run class and triggers using console to check how it works. Am totally new to this environment kindly help

Thanks

Reply
    David Liu
    February 10, 2015 @ 8:59 pm

    Haven’t covered the debug log much sorry! I actually don’t use it to run tests very often either though!

    Reply
    Ramesh
    February 28, 2015 @ 9:39 pm

    Hi David Liu,

    You are Awesome David Liu……..
    I have no idea about test class but i need to learn testclasses with using test class user will automatically created pls help

    Reply
Gajanan
February 5, 2015 @ 12:31 am

How to get PublicId?

Reply
    Gajanan
    February 5, 2015 @ 1:06 am

    Sorry ProfileId.

    Reply
      David Liu
      February 5, 2015 @ 8:13 pm

      Navigate to the Profile record in Salesforce then the ID is in the URL

      Reply
Lawrence Peters
November 20, 2014 @ 3:10 am

Hi David

My name is Lawrence and first of all thanks for all your help. The biggest compliment i want to give you is that there are few people in this world who always see to find the good in others and you are one of them. So keep up the good work.

This is a Class that I have created below:. When I run the test it says Test Method Failed but the Code coverage is 100%. How can this be possible.

@isTest
public class PopResellerANDoNCase {
static testMethod void insertNewCase() {

Account testAccount1 = new Account();

testAccount1.Name=’Test of the Account1′;
testAccount1.type=’Home’;
testAccount1.Shippingcountry=’United Kingdom’;
insert testAccount1;

Case TestCase = new Case();

TestCase.accountid = testAccount1.id ;
insert TestCase;

}
}

Reply
    David Liu
    November 20, 2014 @ 8:22 pm

    Could be many things depending on your trigger or other factors!

    You can try posting this to the forums (with your trigger and more error details) if you’re still stuck!
    https://www.sfdc99.com/forums/forum/beginning-apex/

    Reply
      chitral
      January 7, 2015 @ 3:40 am

      @Lawrence Peters
      buddy add this
      public class TestPopResellerANDoNCase

      and it would work :)

      Reply
chitral
November 7, 2014 @ 12:15 am

hi david,pls help
error
System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []

@isTest
public class TestUserCheckboxField
{
static testMethod void insertNewUser()
{
User userToCreate = new User();
userToCreate.FirstName = ‘aa’;
userToCreate.LastName = ‘ss’;
userToCreate.Email = ‘lamba.piyush19@gmail.com’;
userToCreate.Username = ‘lamba.piyush19@gmail.com’;
userToCreate.Alias = ‘fatty’;
userToCreate.ProfileId = ‘00590000003XMAQ’;

userToCreate.TimeZoneSidKey = ‘America/Denver’;
userToCreate.LocaleSidKey = ‘en_US’;
userToCreate.EmailEncodingKey = ‘UTF-8’;
userToCreate.LanguageLocaleKey = ‘en_US’;

insert userToCreate;
}
}
profile id and email is entered correctly

Reply
dellastreet58
September 19, 2014 @ 2:48 pm

You sure explain apex better than anybody else out there. Thanks a million!

Reply
Somnath Paul
September 9, 2014 @ 2:28 am

Hi David,

Thanks a lot for all your help. I am very new to apex coding. Just wanted to know after successful execution of this test class what would be the result in the application. I was expecting a new User with the given name to be inserted in the application. But i could not find any new user with the username given in the code.

Please let me know if my understanding is correct.

Thanks
Som

Reply
    David Liu
    September 9, 2014 @ 7:56 pm

    Test class data doesn’t save in your org – it runs in the test then everything magically dissappears =)

    Reply
Tirth
September 4, 2014 @ 11:11 pm

Hey David,

Excellent site for the beginners to learn Apex. Keep up the good work!!

I am a beginner so might be a silly question – what’s the difference between public class and private class?

Reply
    David Liu
    September 7, 2014 @ 10:31 pm

    Hhhmmm I always use public so it’s probably not a big deal with classes =)

    Reply
    sravan
    November 10, 2014 @ 2:36 am

    Public class – you can access the class with the org, Private class- you can access with in that class only.

    Reply
Neenu Mathew
August 21, 2014 @ 10:57 pm

Hi David,

While checking debug logs how to recognize which log is the one we are looking at.To be more precise I have a test class and once that test class is run I have to check the log for this test class.I can see a lots of logs coming up.But do not know how to distinguish a trigger,test class etc.Please help.

Reply
    David Liu
    August 21, 2014 @ 10:58 pm

    Clear all your logs right before running the test =) The newest ones show up on top and have an “Unread” flag

    Reply
      Neenu Mathew
      August 21, 2014 @ 11:13 pm

      Appreciate your quick response David.But eventhough I have cleared all the logs and then run this test class we can see other logs coming up.All those have unread flag and again the “Application” would be like “Unknown”,”Browser” etc.If there are 2 or three coming up I would guess and find.But I have seen many logs before even though I did as you said. :(

      Reply
        David Liu
        August 21, 2014 @ 11:20 pm

        You must have a ton of code running in the background to create so many logs!

        Here are some things you can do:
        – Limit only to logs generated by you (check the dev console toolbar)
        – Turn off any integrations you have while testing
        – Do it in sandbox!

        Reply
Steve Kucklinca
August 20, 2014 @ 11:47 am

David,

I am very new to writing triggers and classes. I recently (with help) built this trigger in my sandbox and I know I need code coverage to deploy, but I have no idea where to start for my test class to move it forward. Any guidance would surely be appreciated:

trigger MerchOppsRecords on Merchant_Application__c (after update){

Set accountIds = new Set();
Map accountOpportunityMap = new Map();
// Get the parent Account Ids from all the Merchant Application records,
for(Merchant_Application__c ma : Trigger.new){
accountIds.add(ma.Account_Name__c); // Assuming Account__c is the fields that maps to the Account Object
}

// Query the Opportunity using AccountId and build a map of AccountId to the Opportunity record
// Here the assumption is that One account is tied to only one Opportunity. But if you have multiple opportunities for a single account, the logic must identify the right opportunity
for(Opportunity opp : [Select Id, Name, AccountId from Opportunity where AccountId = :accountIds]){
accountOpportunityMap.put(opp.AccountId,opp);
}

List mOps = new List();

// Iterate again to build the Junction Object Records,
for(Merchant_Application__c ma : Trigger.new){

if(accountOpportunityMap.containsKey(ma.Account_Name__c)){
MerchOpps__c mo = new MerchOpps__c(ChildofOpp__c = accountOpportunityMap.get(ma.Account_Name__c).Id, ChildofMA__c = ma.ID); //how to
mOps.add(mo); // Add the records to the list
}
}

insert mOps; // Insert the junction object records.

}

Reply
    David Liu
    August 20, 2014 @ 10:51 pm

    Imagine what you’d have to do in your Salesforce org to make every line of that trigger run.

    You’d probably create a new Merchant_Application__c record and make sure it has the right fields/relationships set in advance.

    That’s exactly what you need to do in your test class, but programmatically =) Give it a shot and post your code here!

    Reply
Bernard Mesa
August 11, 2014 @ 1:31 pm

Hey David,

First, thank you for this site!! It is a tremendous resource!

I’m new to writing Triggers/Classes/Tests for SalesForce. I’m not new to programming, but definitely new to SalesForce.

I wrote a trigger to detect if an account owner changes, to change the children account owners to inherit the new parent account owner. (I tried to use a workflow rule, but it won’t let me dynamically change account owners).

I tried it out in the Sandbox and it works. However, when I write the test for it, I get this error:

FATAL_ERROR System.DmlException: Update failed. First exception on row 0 with id 001f000000gwo8CAAQ; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, test_trigger: execution of BeforeUpdate

Here is the trigger:

trigger test_trigger on Account (before update)
{
System.debug(‘Test trigger: start’);

//I only want to update one account at a time; this is only for manually changing one account
if(Trigger.new.size() == 1)
{
Account a = Trigger.new[0];
if(!(a.OwnerId.equals(Trigger.old[0].OwnerId)))
{
batchAccountUpdate b = new batchAccountUpdate(a.Id, a.OwnerId);
database.executeBatch(b);
}
}
}

Here is the batchAccountUpdate:

global class batchAccountUpdate implements Database.Batchable
{
String account_id;
String owner_id;
public batchAccountUpdate(String account_id, String owner_id)
{
this.account_id = account_id;
this.owner_id = owner_id;
}
global Database.QueryLocator start(Database.BatchableContext BC)
{
String query = ‘SELECT OwnerId, Name FROM Account WHERE ParentId = \” + account_id + ‘\’ AND OwnerId \” + owner_id + ‘\”;
return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC, List scope)
{
//System.debug(‘Starting for-loop’);
for(Account a : scope)
{
a.OwnerId = owner_id;
}
update scope;
}
global void finish(Database.BatchableContext BC)
{
}
}

Here is the test class:

@isTest

public class TestAcctOwnerUpdate
{
static testMethod void testUpdateOwner()
{
String owner = ‘005i0000000Sk0oAAC’;
String new_owner = ‘005i0000000R2swAAC’;

Account a = new Account(Name = ‘Test Parent Acct’, OwnerId = owner);
insert(a);

Account b = new Account(Name = ‘Test Child Acct’, ParentId = a.Id);
insert(b);

a.OwnerId = new_owner;
update(a);
}
}

Any help would be appreciated, thanks!!!!

Reply
    Bernard Mesa
    August 11, 2014 @ 1:55 pm

    Sorry, I forgot the include all of the error:

    13:28:15:643 FATAL_ERROR System.DmlException: Update failed. First exception on row 0 with id 001f000000gwo8CAAQ; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, test_trigger: execution of BeforeUpdate

    13:28:15:000 FATAL_ERROR caused by: System.AsyncException: Database.executeBatch cannot be called from a batch start, batch execute, or future method.

    13:28:15:000 FATAL_ERROR Trigger.test_trigger: line 12, column 1: []

    13:28:15:000 FATAL_ERROR Class.batchAccountUpdate.execute: line 23,

    Reply
    David Liu
    August 11, 2014 @ 8:27 pm

    Hey Bernard,

    The issue is mainly because you’re calling a batch job from a trigger. Although this is possible, it’s unnecessary since you can simply do your logic in the trigger instead! Batch jobs are used when you need to change a massive amount of records (like 100,000+)!

    So – try to put the batch logic inside your trigger instead. If you absolutely need a batch, try scheduling it so it runs during specific times of the day, instead of using a trigger!

    David

    Reply
      Bernard Mesa
      August 12, 2014 @ 10:20 am

      Thank you, David! I will move all the logic into the trigger, the most amount of records we’ll process is about 1000+. Thanks, again!

      Reply
        David Liu
        August 12, 2014 @ 12:34 pm

        Go get em!! =)

        Reply
          Bernard Mesa
          August 12, 2014 @ 1:44 pm

          That worked beautifully! First deployed code from Sandbox to Production after almost a year of using workflows. It certainly won’t be the last!

          Reply
            David Liu
            August 12, 2014 @ 8:02 pm

            Proud of you Bernard, welcome to the good life!!

            Reply
Sue
July 29, 2014 @ 8:56 pm

Hi David,
I am VERY new and using your tutorial to help me learn Apex. In this lesson, you have created an Apex Class. Are we supposed to copy it to our Sandbox? Are we supposed to make any changes? Are we supposed to run the test? It’s not always clear what we are supposed to do.

Reply
    David Liu
    July 29, 2014 @ 9:54 pm

    Go through Chapter 1 in order and it’ll be more obvious =)

    https://www.sfdc99.com/beginner-tutorials/#beginnerTrigger

    Reply
Kruthi
June 20, 2014 @ 11:09 am

Thanks David for your work.
You are genius, you clear doubts with so much interest and make us understand so minute things. Thanks a ton. God bless you.

Reply
    David Liu
    June 23, 2014 @ 10:56 pm

    Thanks for the kind comment =)

    Reply
Daniel
June 16, 2014 @ 10:18 am

Hello David:

You have a very nice website. I have the following question:

If the purpose of the trigger is to set

userInLoop.ForecastEnabled = true

why don’t you test this is actually true after the instert? It seems to me that your test only ensures that an User has been inserted and not that ForeCastEnables is set to true.

Reply
    David Liu
    June 17, 2014 @ 6:13 pm

    Great observation!

    We don’t do it for simplicity reasons (especially since it’s not required)!

    In Chapter 4 though I teach these concepts =)
    https://www.sfdc99.com/2013/11/02/principles-of-a-good-test-class/

    Reply
Paula
May 25, 2014 @ 9:49 pm

Nice!! @ThatDarnWoman is making progress.

Time Started 5/25/2014 9:46 PM
Class TestForceForecasting
Method Name insertNewUser
Pass/Fail Pass

Reply
    David Liu
    May 26, 2014 @ 12:13 am

    @ThatDarnWoman you are the best!!!

    Reply
Danielle
May 19, 2014 @ 6:34 pm

Hi David,

I started making the test class and keep running in to the same error others have mentioned above. I made sure to have an accurate profile ID and am still not passing when running a test. Any suggestions?

@isTest
public class TestForceForecasting {
static testMethod void insertNewUser() {

User userToCreate = new User();

// Do you recognize these fields?
userToCreate.FirstName = ‘David’;
userToCreate.LastName = ‘Liu’;
userToCreate.Email = ‘dvdkliu+sfdc99@gmail.com’;
userToCreate.Username = ‘sfdc-dreamer@gmail.com’;
userToCreate.Alias = ‘fatty’;
userToCreate.ProfileId = ’00eE0000000Nqk4′;

// Don’t worry about these
userToCreate.TimeZoneSidKey = ‘America/Denver’;
userToCreate.LocaleSidKey = ‘en_US’;
userToCreate.EmailEncodingKey = ‘UTF-8’;
userToCreate.LanguageLocaleKey = ‘en_US’;

insert userToCreate;
}
}

Apex Test Result Detail

Time Started 5/19/2014 6:22 PM
Class TestForceForecasting
Method Name insertNewUser
Pass/Fail Fail
Error Message System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []
Stack Trace Class.TestForceForecasting.insertNewUser: line 21, column 1

Reply
    David Liu
    May 19, 2014 @ 7:12 pm

    Try this!

    1. Make sure the profile ID is case sensitive!
    – You can check to see if you have a correct profile if you enter the ID in your URL and go: ….force.com/00eE0000000Nqk4
    2. If the above doesn’t work, take a screenshot of the following and send to me (if you are comfortable with it):
    – The actual profile page (including the URL!)
    – The test class and its error message

    The beauty of working with code is that code never has errors, the worst case scenario is that we are not giving our code the right inputs!

    David

    Reply
      Danielle
      May 21, 2014 @ 2:47 pm

      Time Started 5/21/2014 2:44 PM
      Class TestForceForecasting
      Method Name insertNewUser
      Pass/Fail Fail
      Error Message System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_USERNAME, Duplicate Username.Another user has already selected this username.Please select another.: [Username]
      Stack Trace Class.TestForceForecasting.insertNewUser: line 21, column 1

      This is the error I get now, which seems like it has already run and been successful but it has yet to pass. I ran it 4 times.

      I also checked the profile ID and it is good.

      @isTest
      public class TestForceForecasting {
      static testMethod void insertNewUser() {

      User userToCreate = new User();

      // Do you recognize these fields?
      userToCreate.FirstName = ‘David’;
      userToCreate.LastName = ‘Liu’;
      userToCreate.Email = ‘dvdkliu+sfdc99@gmail.com’;
      userToCreate.Username = ‘sfdc-dreamer@gmail.com’;
      userToCreate.Alias = ‘fatty’;
      userToCreate.ProfileId = ’00eE0000000Nqk4′;

      // Don’t worry about these
      userToCreate.TimeZoneSidKey = ‘America/Denver’;
      userToCreate.LocaleSidKey = ‘en_US’;
      userToCreate.EmailEncodingKey = ‘UTF-8’;
      userToCreate.LanguageLocaleKey = ‘en_US’;

      insert userToCreate;
      }
      }

      Is the code. Do you have email to send? I will take a picture and send you the page as well. Thank you!

      Reply
        David Liu
        May 22, 2014 @ 5:23 pm

        SWEET! Almost there Danielle!

        Simply change the username from sfdc-dreamer@gmail.com to something 100% unique!

        In Salesforce, you can’t have the exact same username as any other person in the world, even during Apex and test classes! So you simply need to choose one that you know no one else will ever use =)

        It’ll work after this!
        David

        Reply
  • Pingback: What (approximately) 48 hours with Apex has taught me | SFDCinSeatown

  • Pankaj Kumar
    April 21, 2014 @ 12:22 am

    Hi David, for an apex code to be deployed from Sandbox to Production we must have overall 75% code coverage. what if we deploy it from sandbox org to sandbox. can we still deploy if overall code coverage < 75%.

    Reply
      David Liu
      April 21, 2014 @ 8:16 pm

      Sandbox to sandbox you don’t need any code coverage =)

      Reply
    Afreen Khan
    April 15, 2014 @ 6:48 pm

    Hello David,

    I am quite new to salesforce and your blog is helping me alot to learn many wonderful things.

    While running the test for my testclass i got the below error.

    System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []

    Could you please tell me what went wrong

    Reply
      David Liu
      April 15, 2014 @ 7:26 pm

      Make sure you’re populating the ProfileId field with an actual Profile ID from your org – it’ll be different than the one I have! If you scroll below in the comments someone else had the exact same error and solved it – so this’ll definitely work!

      Reply
        Vishy S
        April 27, 2014 @ 5:02 am

        Hi David,
        I suppose it’s a good practice not to hard code these values in test classes as it may give the same exception when tdeployed to production. Instead you can use a system utility class to build a logic to get the profile id.

        Reply
          David Liu
          April 27, 2014 @ 4:25 pm

          Correct!!

          In this case, it’s not too big a deal because t he System Admin profile and ID is always the same in sandbox and prod (custom profiles however are not)! But there are very few exceptions like these!!

          Reply
        Tim Andrews
        April 7, 2015 @ 6:11 am

        Viola! That worked!

        Reply
    Raj
    April 10, 2014 @ 1:28 am

    Hi David,

    Appreciate for your efforts on this site and i have starting problem.

    test class in not running successfully , below is the error message:

    Time Started 4/10/2014 1:19 AM
    Class TestForceForecasting
    Method Name insertNewUser
    Pass/Fail Fail
    Error Message System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []
    Stack Trace Class.TestForceForecasting.insertNewUser: line 21, column 1

    Reply
      David Liu
      April 10, 2014 @ 11:35 pm

      Make sure the Profile ID you use is actually valid! Every org will have a different value.

      Reply
        Raj
        April 11, 2014 @ 6:13 am

        Hi David,

        thanks for your response,even after using the correct Salesforce.com Organization ID,the test run is failed.

        any other reason,also for FYI,i am using the free developer edition.

        Reply
          David Liu
          April 11, 2014 @ 10:52 pm

          Free developer edition will work too!

          Can you take a screenshot of the error message as well as the trigger & test class? Should be an easy solution just need to see what the configuration is!

          (P.S. double check all the code is exactly the same, except for IDs, and in the right place!)

          David

          Reply
            Raj
            April 12, 2014 @ 9:56 pm

            Hi David,

            below are the codes and error message:

            trigger ForceForecasting on User (before insert) {
            for (User userInLoop : Trigger.new) {
            userInLoop.ForecastEnabled = true;
            }
            }

            ____________________________________

            @isTest
            public class TestForceForecasting {
            static testMethod void insertNewUser() {

            User userToCreate = new User();

            // Do you recognize these fields?
            userToCreate.FirstName = ‘Raj’;
            userToCreate.LastName = ‘Prasad’;
            userToCreate.Email = ‘Rajpra145@gmail.com’;
            userToCreate.Username = ‘Rajpra145@gmail.com’;
            userToCreate.Alias = ‘praraj145′;
            userToCreate.ProfileId = ’00D90000000oTib’;

            // Don’t worry about these
            userToCreate.TimeZoneSidKey = ‘America/Denver’;
            userToCreate.LocaleSidKey = ‘en_US’;
            userToCreate.EmailEncodingKey = ‘UTF-8’;
            userToCreate.LanguageLocaleKey = ‘en_US’;

            insert userToCreate;
            }
            }

            _________________________________________

            Time Started 4/12/2014 9:55 PM
            Class TestForceForecasting
            Method Name insertNewUser
            Pass/Fail Fail
            Error Message System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []
            Stack Trace Class.TestForceForecasting.insertNewUser: line 21, column 1

            Reply
              David Liu
              April 13, 2014 @ 8:47 pm

              Found it!

              Looks like you accidentally used your Organization ID instead of a System Admin Profile ID. I know this because org IDs begin with 00D and Profile IDs begin with 00e:
              http://www.fishofprey.com/2011/09/obscure-salesforce-object-key-prefixes.html

              You can find the ID exactly like this video does at the 5:40 mark:

              Hope this helps =)
              David

              Reply
            Raj
            April 14, 2014 @ 2:44 am

            Hi David,

            You are superb,awesome.

            Thank you, the test class is now running successfully.

            Reply
    Sandeep
    April 10, 2014 @ 12:01 am

    David you are the best.. You are a life saver… What you are doing is fantastic..Thanks a lot

    Reply
      David Liu
      April 10, 2014 @ 12:05 am

      High five!!!

      Reply
    Auro
    March 14, 2014 @ 9:18 am

    Hi David,

    First of all thank you so much for this wonderful webpage. It gives lots of confidence to ppl like me who want to get into apex coding. Coding has been a show stopper always and I wanted to overcome it. Thanks to you for helping us.

    I tried running the test class as below and I got the below error

    Time Started 3/14/2014 11:02 AM
    Class UserCreate
    Method Name insertNewUser
    Pass/Fail Fail
    Error Message Internal Salesforce Error: 58440344-50072 (-276971633) (-276971633)
    Stack Trace

    Class Details

    @isTest
    public class UserCreate {
    static testMethod void insertNewUser(){
    User freshUser = new User();
    freshUser.FirstName=’NNN’;
    freshUser.LastName=’NN’;
    freshUser.Email=’NN@gmail.com’;
    freshUser.UserName=’NN@gmail.com’;
    freshUser.Alias=’NN111′;
    freshUser.ProfileId = ’00ei0000000rTfp123′;
    freshUser.TimeZoneSidKey = ‘America/Denver’;
    freshUser.LocaleSidKey = ‘en_US’;
    freshUser.EmailEncodingKey = ‘UTF-8’;
    freshUser.LanguageLocaleKey = ‘en_US’;

    insert freshUser;

    }
    }

    I am able to run the test class successfully if I change the method name to
    public static void insertNewUser()

    Any reasons why ? Please advise.

    Reply
      Auro
      March 14, 2014 @ 9:28 am

      Auro: I am able to run the test class successfully but the user record is not getting created now. I am not sure where I am going wrong. Please assist.

      Reply
        Auro
        March 14, 2014 @ 9:58 am

        The test run seems to have passed, I get the below message with a GREEN tick mark. Test Run: 2014-03-14 11:53:14
        (0/0) Test Methods Passed. The test run details not coming in View History link too. Any Suggestions David ?

        Reply
          David Liu
          March 15, 2014 @ 11:33 am

          Hey Auro – note that anything created in the test doesn’t actually stay in your org! They just exist temporarily for the test then disappear forever =)

          So in short – what you’ve done is perfect!

          Reply
            Anonymous
            March 26, 2014 @ 7:31 am

            Hey David, thank you so much :-). Truly appreciate your efforts in getting this site up for beginners like me :-)

            Reply
              David Liu
              March 26, 2014 @ 10:05 am

              Thank you for reading – tell your friends!

              Reply
    Anonymous
    March 12, 2014 @ 12:00 am

    Since our trigger has only five lines of code, we need to run at least four of them, rounding up

    Reply
      David Liu
      March 12, 2014 @ 12:04 am

      Correct =)

      4 out of 5 lines is 80%, PASS!!
      3 out of 5 lines is 60%, FAIL!!

      75% is the minimum!
      David

      Reply
    eshaan
    January 21, 2014 @ 5:35 am

    hey David!!! Got it, you’ve already explained this in next page… :-)

    Reply
      David Liu
      January 21, 2014 @ 8:57 pm

      ^_^

      Reply
    eshaan
    January 21, 2014 @ 5:33 am

    Hi David, Can you please explain ‘ @isTest
    public class TestForceForecasting {
    static testMethod void insertNewUser() {

    User userToCreate = new User();’ in the way you explained creating trigger.plzzz

    Reply
    Anonymous
    November 21, 2013 @ 10:09 am

    This Website is Awesome

    Reply
    Ranjan
    November 13, 2013 @ 2:35 am

    Hii David !!

    Thanx man,I am very new to apex classes and triggers..I search around every where to find some good stuff,which can help me out..finally I got this..eagerly waiting for your next video tutorial and next session..

    1 more thing I am having too much trouble with inner part of trigger ,I mean why we are using — >>
    for(Object instance : Trigger.new/old), why we are using “id” instead of using the actuall API name for the master object..I tried to write to apex trigger for my objects..it worked ..but it just that ..i am not getting the flow properly..hope u’ll help me out..waitng for your reply as well as some more superb sessions :) ..

    Reply
      David Liu
      November 13, 2013 @ 7:43 pm

      Glad you like the site Ranjan!

      IDs in Salesforce are like social security numbers! They are the one unique identifier for each record. When populating lookup fields in Salesforce, it looks like you’re populating a record name but in the background, Salesforce is actually using the record ID! This is because two records can have the exact same name, while two records cannot have the same ID.

      Hope this answers your question – let me know if I didn’t understand it correctly!
      David

      Reply
        Ranjan
        November 13, 2013 @ 9:41 pm

        I have understood that..but my question is,at the time ,we do trigger for child object…for example:
        i have a merchendise object …and line item is a child object of it…and i want if some field gets updated in merchendise..some other field in line item..should also update,,So for this we do something like this
        for(Merchendise__c merc:trigger.new)
        {
        LineItem item =new LineItem();
        item.Merchendice__c=:merc.id;
        }
        So here is my Question..why we are putting merc.id instead of merc.Merchandise__c ,,which is the record name for the object….??

        Reply
          David Liu
          November 13, 2013 @ 9:54 pm

          Hey Ranjan,

          Awesome seeing your code!!

          Lookup/master-detail fields (in this case, Merchendise__c) are always populated by a record ID only! merc.Merchandise__c is actually interpreted by Salesforce as a custom field called “Merchandise” on the record. I can tell it’s a custom field because it has “__c” after it! If this custom field has the value of an ID within it though, it actually will work in your code! Anything else (including a name) won’t work unless it is a valid 15 or 18 digit ID.

          Also – you may want to remove the colon (:) in this line before the “merc”:
          item.Merchendice__c = merc.id;

          Those colons are only used in SOQL bind variables:
          https://www.sfdc99.com/2013/11/04/using-apex-variables-in-a-soql-query/

          Hope this helps!
          David

          Reply
        Ranjan
        November 13, 2013 @ 10:44 pm

        Here’s my full code

        trigger LineItemTrigger on Merchendise__c (after insert,after update) {

        List lineitem=new List();
        List lineitem1=new List();
        for(Merchendise__c merc:trigger.new){

        if(merc.Quantity__c>50){
        lineitem=[select Unit_Price__c from Line_Item__c where Merchendise__c=:merc.id];

        }

        }
        for(Line_Item__c item:lineitem)
        {
        item.Unit_Price__c = 20;
        lineitem1.add(item);
        }

        insert lineitem1;
        update lineitem1;
        }

        Reply
          David Liu
          November 14, 2013 @ 8:20 pm

          Hey Ranjan,

          So the question in a nutshell is – why in the SOQL query are we doing Merchendise__c=:merc.id instead of Merchendise__c=:merc.Merchendise__c

          The reason is because we are comparing different objects. On the left hand side of the equation, we are using a Line_Item__c field. On the right hand side of the equation we are using a Merchendise__c field. The field on the left is an ID field (because it is a lookup), so the field on the right must be an ID too!

          I hope this helps a little =) Let me know if I’m not understanding the question!
          David

          Reply
    Ales
    October 19, 2013 @ 12:14 pm

    Hi David,
    Great job with your site! Love it and so appreciate your kindness. Bless you!!!

    You helped me to develop the following trigger where I make a copy of the system task table’s standard field ActivityDate. Now I would like to write a test class for the trigger. In order to have 100% code cover, I need to create a task with a due date and make sure that the custom field ,CopyOfActivityDate__c, is set to the activity date.

    Next, I need to update the activity date and make sure that CopyOfActivityDate__c is updated as well. Correct? I have started creating the test calss but need help with it. Thank you in advance.

    Here is the trigger that you helped me with:

    trigger CopyActivityDate on Task (after insert, after update) {

    //Bulkify by making a list of task that need updating

    List ListOfTaskToUpsert = new List();

    // for each new Task created,
    // make a copy ActivityDate to CopyOfActivityDate__c and
    // add the task Id to the ListofTaskToUpsert list

    list UpdatedTaskList =
    [SELECT tl.ActivityDate, tl.Id
    FROM Task tl
    Where tl.Id IN :Trigger.new];

    for (Task utl: UpdatedTaskList) {
    boolean IsUpdateActivityDate = true;

    if (Trigger.isUpdate) {

    // Trigger.oldMap gets the version of your object before the update.
    //This doesn’t work for insert triggers

    Task oldTask = Trigger.oldMap.get(utl.Id);
    if (oldTask.ActivityDate == utl.ActivityDate) {
    IsUpdateActivityDate = false;
    }
    }

    if (IsUpdateActivityDate) {
    ListOfTaskToUpsert.add(new Task(Id = utl.Id, CopyOfActivityDate__c = utl.ActivityDate));
    }
    }
    Upsert ListOfTaskToUpsert;

    }

    Here is my attempt at starting to class. I know I’ve created a task here but do not know how to proceed. Your help will be greatly appreciated.

    @isTest
    public class TestActivityDate {
    static testMethod void insertNewTask() {
    Task taskToCreate = new Task();
    // create task
    taskToCreate.subject = ‘Next Meeting’;
    taskToCreate.ActivityDate = date.newinstance(2013, 12, 25);
    taskToCreate.status = ‘Not Started’;
    Insert taskToCreate;
    }
    }

    Reply
      David Liu
      October 19, 2013 @ 4:59 pm

      Ales,

      I am so proud of you, this is a wonderful trigger you’ve written!

      I copied all your code directly into my instance (Check it out by logging in to SFDC99!) and got 100% test coverage without any changes! So you’ve certainly done a good job =)

      The reason you’re getting 100% is because your trigger runs on any new Task with a new ActivityDate. Since your test class creates a new Task with a new ActivityDate, you’ll get good coverage with it!! Know that you actually only need 75% coverage to deploy something, so if you’re ever stressing to get 100% that’s never required!

      One thing you can add to your test to make your code truly bulletproof is a System.assertEquals() method. This is a like a double check clause in your test class to make sure everything works.

      Try adding this right after inserting your task in the test class:
      Task createdTask = [SELECT Id, CopyOfActivityDate__c FROM Task WHERE Id = :taskToCreate.Id];
      System.assertEquals(createdTask.CopyOfActivityDate__c, taskToCreate.ActivityDate);

      All this does is query for the new values of your created task, then make sure that the ActivityDate copied perfectly into your CopyOfActivityDate__c. I tested this as well and it works 100%!

      Good job Ales!
      David

      Reply
      neha
      November 13, 2013 @ 11:12 pm

      Sorry.. I am beginner in learning the code…
      I have 2 doubts over here

      1)boolean IsUpdateActivityDate = true;(what do this statement exactly do?)

      2)In test class instead of creating a a new task.. if i want to update the existing task.. what should i do??

      Reply
        David Liu
        November 14, 2013 @ 8:26 pm

        No problem Neha, I’m happy to help!

        So you are referring to Ales’s comment that was made on October 19th, 2013.

        What she’s doing is creating a variable to track a true or a false. She named the variable IsUpdateActivityDate, but she could have named it anything. For example, she could’ve called it “updateTheActivity” because she’s using that variable to see if she should update the activity record later!

        Here are some posts that might help you understand the concepts:
        Variables: https://www.sfdc99.com/2013/09/28/data-types-strings-dates-numbers-and-sobjects/
        Updating records: https://www.sfdc99.com/2013/10/13/creating-updating-and-deleting-records/

        As for your question about updating a task in your test class, the best way to do this is to create a task, insert it, then update it. Here’s an example:

        Task t = new Task();
        // Fill in whatever required fields are needed
        insert t;

        // Now we update it again
        t.Subject = ‘Update Me!’;
        update t;

        Hope this helps Neha!
        David

        Reply
          neha
          November 14, 2013 @ 9:39 pm

          Thank you ..David.. Your reply helped me to understand.

          Reply
    axis kumar
    June 4, 2013 @ 4:10 am

    Very nice material for beginners to learn Apex ….

    Can we expect some more sessions on Apex please?

    Reply
      David Liu
      June 5, 2013 @ 12:07 am

      Axis Kumar – happy to hear you’re getting value from sfdc99!

      A new post is up and you can expect at least one per week!

      David

      Reply
        Peter Noges
        June 18, 2013 @ 9:14 pm

        Rock on, David!

        Reply

    Leave a Reply Cancel reply

    Your email address will not be published. Required fields are marked *


    *

    *

    Theme: Simple Style by Fimply