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
Hello!
I have the following apex class:
public class RequerimientosDeComercialController {
public List ventaTabla {get;set;}
public RequerimientosDeComercialController(){
String currentRecordId = ApexPages.CurrentPage().getparameters().get(‘id’);
List ventaLista = [SELECT Cadena__c, Formato__c, Producto__c, Medida__c, Marca__c, RequerimientosEspeciales__c, RequerimientosDiseno__c FROM Venta__c WHERE RequerimientosDiseno__c != null and Campana__c=:currentRecordId];
Map mapa = new Map();
for(Venta__c venta : ventaLista){
String key = venta.Cadena__c+’-‘+venta.Formato__c+’-‘+venta.Producto__c+’-‘+venta.Medida__c+’-‘+venta.Marca__c;
If(!mapa.containsKey(key)){
mapa.put(key,venta);
}
}
ventaTabla = mapa.values();
}
}
***** but I can’t finish the test class ***
@isTest
public class RequerimientosDeComercialControllerTest {
@testSetup static void setup(){
List testVentaLista = [SELECT
Cadena__c,
Formato__c,
Producto__c,
Medida__c,
Marca__c,
Requerimientos__c
FROM Venta__c
WHERE Requerimientos__c != null and Campana__c=’AAAAAAAAAAA’];
Campana__c objCampanaTest = new Campana__c();
objCampanaTest.Id = ‘AAAAAAAAAAA’;
insert objCampanaTest;
}
@IsTest
static void testVentaTabla() {
Test.startTest();
try{
RequerimientosDeComercialController.ventaTabla();
}catch(Exception ex){
System.debug(‘ ** ERROR ** ‘ + ex.getMessage());
}
Test.stopTest();
}
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);
}
}
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; }
}
}
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;
}
}
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?
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;
}
}
@Mike – one thing that sticks you need to remove the //comments
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
Try using a system debug in there =) Very interesting why it doesn’t work!
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.
@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;
}
}
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 ?
Looks like your coding editor is out of sync with your org! Or you have the wrong org setup!
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.
good question David please reply
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!
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
Update: Using query builder, select Id from attachment returns no rows, but there are attachments in my org??
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…
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;
}
}
}
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;
}
}
}
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;
}
}
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.
That’s a lot of code!!!!!
please help me in this
just help to covered atleast 75%. ASAP
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.
I don’t see any changes after write these codes
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;
}
}
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?
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!
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.
My pleasure Nidhu =) Happy to help! That’s my life’s calling!
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!!!
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’);
}
}
}
}
}
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?
User is a standard SObject =)
User is a standard object and we are creating new record for User object.
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
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: []
Try to guess what you’re getting this error! What do you think? =)
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!
Very proud of you Troy!!!
Keep it up you’ll be surprised how quickly you can learn!
David
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();
}
}
Too much code to debug, try the official dev forums or hopefully someone else here can help out!
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.
Most of this can be done without code!
For the rest, I recommend the developer forums =)
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.
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;
}
}
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
Actually you know what – you should be using an “after insert” trigger instead =)
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
Quadruple check it’s the right ID
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’);
}
}
}
Can’t write code for you sorry!
Try writing it first then posting about it.
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
Your ProfileID=’00590000002VTKN’ does not looks like a ProfileID but an UserId, ProfileId starts with 00e
Hi Pedrog
Thank you for your reply, at last I wrote successful test trigger :)
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
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.
Well done well done sir!
good example anyone can easily learn through this
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.
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 ?
Hi,
Is it possible for users to unsubscribe email notification for specific SARs
Hi David,
When we run the created create contact test class, does contact actually get created?
Thank you.
Nope!
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
Haven’t covered the debug log much sorry! I actually don’t use it to run tests very often either though!
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
How to get PublicId?
Sorry ProfileId.
Navigate to the Profile record in Salesforce then the ID is in the URL
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;
}
}
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/
@Lawrence Peters
buddy add this
public class TestPopResellerANDoNCase
and it would work :)
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
You sure explain apex better than anybody else out there. Thanks a million!
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
Test class data doesn’t save in your org – it runs in the test then everything magically dissappears =)
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?
Hhhmmm I always use public so it’s probably not a big deal with classes =)
Public class – you can access the class with the org, Private class- you can access with in that class only.
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.
Clear all your logs right before running the test =) The newest ones show up on top and have an “Unread” flag
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. :(
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!
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.
}
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!
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!!!!
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,
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
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!
Go get em!! =)
That worked beautifully! First deployed code from Sandbox to Production after almost a year of using workflows. It certainly won’t be the last!
Proud of you Bernard, welcome to the good life!!
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.
Go through Chapter 1 in order and it’ll be more obvious =)
https://www.sfdc99.com/beginner-tutorials/#beginnerTrigger
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.
Thanks for the kind comment =)
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.
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/
Nice!! @ThatDarnWoman is making progress.
Time Started 5/25/2014 9:46 PM
Class TestForceForecasting
Method Name insertNewUser
Pass/Fail Pass
@ThatDarnWoman you are the best!!!
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
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
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!
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
Pingback: What (approximately) 48 hours with Apex has taught me | SFDCinSeatown
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%.
Sandbox to sandbox you don’t need any code coverage =)
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
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!
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.
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!!
Viola! That worked!
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
Make sure the Profile ID you use is actually valid! Every org will have a different value.
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.
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
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
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
Hi David,
You are superb,awesome.
Thank you, the test class is now running successfully.
David you are the best.. You are a life saver… What you are doing is fantastic..Thanks a lot
High five!!!
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.
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.
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 ?
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!
Hey David, thank you so much :-). Truly appreciate your efforts in getting this site up for beginners like me :-)
Thank you for reading – tell your friends!
Since our trigger has only five lines of code, we need to run at least four of them, rounding up
Correct =)
4 out of 5 lines is 80%, PASS!!
3 out of 5 lines is 60%, FAIL!!
75% is the minimum!
David
hey David!!! Got it, you’ve already explained this in next page… :-)
^_^
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
This Website is Awesome
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 :) ..
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
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….??
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
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;
}
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
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;
}
}
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
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??
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
Thank you ..David.. Your reply helped me to understand.
Very nice material for beginners to learn Apex ….
Can we expect some more sessions on Apex please?
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
Rock on, David!