Test class for trigger - triggers

I just wrote this trigger and it seems to be working fine in dev, I need to move it into production, however, the test class I wrote passes the test but does not cover the trigger. Any help would be greatly appreciated. I am a bit green here. I know I should be inserting a contact (the account is a req field) then updating the contact field I just have no earthly clue how to do taht. Thank you
trigger PropOwned on Contact (after update) {
for (Contact c : Trigger.new) {
McLabs2__Ownership__c ownNew = new McLabs2__Ownership__c();
Contact oldContact = Trigger.oldMap.get(c.id);
if (c.One_Prop_Owned__c != oldContact.One_Prop_Owned__c && c.One_Prop_Owned__c != null) {
ownNew.McLabs2__Contact__c = c.id;
ownNew.McLabs2__Property__c = c.One_Prop_Owned__c;
insert ownNew;
}
}
}
This is the test class I wrote.
#isTest
public class TestOwnership {
static testMethod void createOwnership() {
McLabs2__Ownership__c ownNew = new McLabs2__Ownership__c();
ownNew.McLabs2__Contact__c = 'Michael Webb';
ownNew.McLabs2__Property__c = '131 West 33rd Street';
insert ownNew;
}
}

Your test class just creates a McLabs2__Ownership__c object and inserts this object in database. As a result of this trigger on McLabs2__Ownership__c(if exist) will be invoked, but you have to test a trigger on Contact object. Thus you need to insert an account and after that update it because your contact trigger works in after update mode.
So, you need something like that
#isTest
private class TestOwnership {
static testMethod void whenContactUpdatedNewOwnershipIsInserted() {
// create contact, you have to replace 'value1' with appropriate data type
Contact contact = new Contact(name = 'Test Contact', One_Prop_Owned__c = 'value1');
insert contact;
contact.One_Prop_Owned__c = 'value2'; // you have to replace value2 with appropriate data type
update contact;
// in this place you should has only one record of McLabs2__Ownership__c in database, because in test context real data isn't visible
List<McLabs2__Ownership__c> ownerships = [SELECT Id, McLabs2__Contact__c, McLabs2__Property__c FROM McLabs2__Ownership__c];
System.assertEquals(1, ownerships.size());
System.assertEquals(contact.Id, ownerships[0].McLabs2__Contact__c);
System.assertEquals(contact.One_Prop_Owned__c, ownerships[0].McLabs2__Property__c);
}
}
Read the following articles which might be pretty useful for you:
Apex Trigger best practice
SOQL in loop

Related

Clone Opportunity records with all the fields without using standard clone() method?

I have try to clone Opportunity records and done till 3 fix field But I need for all fields.But without using clone() method.
Code -
public class Cloningwithout {
public static void insertclone(){
Opportunity opp = new Opportunity(Name='Opportunity2', CloseDate=date.parse('06/07/2012'),StageName='Prospecting');
insert opp;
ID Oppid =opp.ID;
clone1(Oppid);
}
public static void clone1(String IDs){
Opportunity sourceopp = [SELECT Id,Name,CloseDate,StageName from Opportunity Where Id=:IDs];
Opportunity targertopp = new Opportunity();
targertopp.Name = sourceopp.Name;
targertopp.CloseDate = sourceopp.CloseDate;
targertopp.StageName = sourceopp.StageName;
insert targertopp;
} }
maximum trigger depth exceeded
Your trigger runs after Opportunity is inserted. It inserts new opportunity, which causes the trigger to run, which inserts new opportunity... Until about 16 recursive operations, then SF terminates your action. Using clone() or not has nothing to do with it.
What are you trying to do, insert just once and then skip the trigger? You could have helper checkbox on Opportunity or a static variable
trigger CloneTrigger on Opportunity (after insert) {
static Boolean skip = false;
if(!skip){
skip = true;
Opportunity[] ls=new Opportunity[]{};
for(Opportunity o: trigger.new){
Opportunity obj=new Opportunity();
// obj.id = null;
obj.name=o.name;
obj.CloseDate = o.CloseDate;
obj.StageName = o.StageName;
ls.add(obj);
}
insert ls;
}
}

Test Class in apex

So i am new to salesforce and i finished my training and now im working on a project. But on my project i have stumbled on a test class that i am not finding a way to write it, so i would appreciate if anyone can help me figure out a way to write it. Here is the code:
public class AP01_Opportunity
{
//Method to create a new service contract when opportunity = Gagné
public static void CreateContract(List<Opportunity> listOpp, Map<Id, Opportunity> oldMap)
{
//Variable Declaration
ServiceContract sc;
List<ServiceContract> listSCToAdd = new List<ServiceContract>();
List<ContractLineItem> listContractItems = new List<ContractLineItem>();
List<Opportunity> listOppGagne = new list<Opportunity>();
//Loop in list of opportunities
for(Opportunity opp : listOpp)
{
if(opp.StageName == Label.ClotureGagne && !oldMap.get(opp.Id).isWon)
{
listOppGagne.add(opp);
}
}
//check if list has opportunity becoming won
if(listOppGagne.size() > 0){
Map<Id, Opportunity> mapOppGagne = new Map<Id, Opportunity> ([SELECT Id,
Name,
StageName,
Pricebook2Id,
Account.Name,
(SELECT Id,
PricebookEntryId,
PricebookEntry.Name,
Quantity,
UnitPrice
FROM OpportunityLineItems)
FROM Opportunity
WHERE Id in :listOppGagne]);
for( Opportunity opp : listOppGagne )
{
//Create new service contract
sc = new ServiceContract();
sc.Name = opp.Name;
sc.ApprovalStatus = Label.Activated;
sc.OpportunityId__c = Id.valueOf(opp.Id);
sc.Pricebook2Id = opp.Pricebook2Id;
sc.StartDate = Date.today();
listSCToAdd.add(sc);
}
if(listSCToAdd.size() > 0){
insert listSCToAdd;
Opportunity currentOpp;
ContractLineItem cli;
Id oppId;
for(ServiceContract servcont : listSCToAdd)
{
oppId = servcont.OpportunityId__c;
if(mapOppGagne.containsKey(oppId))
{
currentOpp = mapOppGagne.get(oppId);
//copy the oppLineItems per opportunity to the respective Service Contract
for(OpportunityLineItem items : currentOpp.OpportunityLineItems)
{
cli = new ContractLineItem();
cli.PricebookEntryId = items.PricebookEntryId;
cli.Quantity = items.Quantity;
cli.UnitPrice = items.UnitPrice;
cli.ServiceContractId = servcont.Id;
listContractItems.add(cli);
}
}
}
if(listContractItems.size() > 0)
{
insert listContractItems;
}
}
}
}
}
this code is a trigger that creates a new service contract record with contract line items copied from the opportunity line items, when the opportunity stage changes to "Cloturé Gagné" which means closed won in french.
Thank you in advance.
In order to write a simple test class I would recommend you to use the following guide: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm
The idea is simple: Lets say you create an Opportunity in your Test class and make an insert or update in your case - your trigger class will automatically fire and run the code from your AP01_Opportunity class. You can put some
System.debug('some message');
to check if your logic works as expected and also which code blocks are executed

Trigger to copy image from child record to parent record

I am trying to write a trigger that will update a RTA field on a parent object with an image from a RTA field on the child object.
I am getting the below error when creating the child object
Apex trigger Updateparent caused an unexpected exception, contact your administrator: Updateparent: execution of AfterInsert caused by: System.StringException: Invalid id: (.....IMAGE IS DISPLAYED HERE....)External entry point.
Info
Man Utd is the child object
Account is the parent object
Image__c is the RTA field on the child object
Copy_image__c is the RTA field on accounts
Here is the trigger code
trigger Updateparent on Man_Utd_1__c (after insert, after update) {
Map<ID, Account> parentAccounts = new Map<ID, Account>();
List<Id> listIds = new List<Id>();
for (Man_Utd_1__c childObj : Trigger.new) {
listIds.add(childObj.Image__c);
}
parentAccounts = new Map<Id, Account>([SELECT id, (SELECT ID, Image__c FROM Man_Utd_s__r) FROM Account WHERE ID IN :listIds]);
for (Man_Utd_1__c manu : Trigger.new) {
Account myParentAccounts = parentAccounts.get(manu.Image__c);
myParentAccounts.Copy_image__c = manu.Image__c;
}
update parentAccounts.values();
}
Can anyone advise on how to rectify this or if it is even possible to do?
EDIT to answer comments
This one works for me, there's a slight modification around the null check. Give it a go? The field is called Image__c both on Account and Contact.
trigger rollupImage on Contact (after insert, after update) {
Set<Account> parents = new Set<Account>();
for (Contact child : trigger.new) {
if(child.AccountId != null && child.Image__c != null){
parents.add(new Account(Id = child.AccountId, Image__c = child.Image__c));
}
}
if(!parents.isEmpty()){
List<Account> toUpdate = new List<Account>();
toUpdate.addAll(parents);
update toUpdate;
}
}
ORIGINAL
The error
It's all written there ;)
List<Id> listIds = new List<Id>();
for (Man_Utd_1__c childObj : Trigger.new) {
listIds.add(childObj.Image__c); // boom happens here?
}
You're assigning rich text area value (very long string with encoded image in it) to Id variable (15 or 18 char special string)
Try like this:
Set<Id> ids = new Set<Id>(); // Set will ensure we won't have duplicate values
for (Man_Utd_1__c childObj : Trigger.new) {
ids.add(childObj.Account__c);
}
Optimization - round 1
In the second loop you're setting the Copy_Image__c field but on the local copy of Account (local variable in the scope of the loop). I'm not sure setting it there will propagate the change to the parent acc (it might be a full copy and not a reference to the item in the map. You could put it back (parentAccounts.put(manu.Account__c, myParentAccounts)) to the map or just do the image assignment directly:
parentAccounts = new Map<Id, Account>([SELECT id FROM Account WHERE ID IN :ids]);
// I've removed the subquery, you don't need it, right?
for (Man_Utd_1__c manu : Trigger.new) {
if(parentAccounts.containsKey(manu.Account__c)){
parentAccounts.get(manu.Account__c).Copy_image__c = manu.Image__c;
}
}
update parentAccounts.values();
Optimization - round 2
It looks bit stupid - we query for Accounts but all we need to fetch is the Id... But we know the Id already, right? So - behold this "pro trick" (shared just because my colleague is a big fan of Man U ;))
trigger Updateparent on Man_Utd_1__c (after insert, after update) {
Set<Account> parents = new Set<Account>();
for (Man_Utd_1__c child : trigger.new) {
if(child.Account__c != null){
parents.add(new Account(Id = child.Account__c, Copy_Image__c = child.Image__c));
}
}
if(!parents.isEmpty()){
List<Account> toUpdate = new List<Account>();
toUpdate.addAll(parents);
update toUpdate;
}
}
Note: Optimization is the key thing while writing trigger.
While writing trigger make sure you follow all the best practises:
Keynotes On Trigger:
OPTIMIZATION - I have specified it in Uppercase and in first line because its the key thing while writing logic
Proper indentation and code commenting, so that anyone who works on the same code will easily understand the logic by just glancing on the comments. Make sure you update lastModifiedBy line on initial comments so that it will be helpful to keep a trace who worked last/updated last and on what date. Better keep proper code comments on every line- IF NEEDED ONLY
Variables with proper names ex: if var of list type then 'lst' prefix or 'List' postfix and then the proper name ex: lstContactsToInsert OR lstContactsToUpdate
Always create a seperate handler class and don't write all the logics on trigger itself 'AS A BEST PRACTISE TO FOLLOW'
Have proper trigger contexts. Know when to use proper trigger contexts through salesforce documentations on trigger. Use 'Before' contexts if it can be handled using this, If Not then go for 'After' contexts so you limit DML's.
Keynotes On Handler:
The First 3 steps as mentioned for trigger applies here as well
Use common private methods where you write logic and use it in other methods
Keynotes On TestClass:
Always write a test class utilizing 'GENERIC TEST DATA CLASS' in your test class.
Use proper test method names like: test_Method_One 'OR' testImageUpdates as such
Use asserts and test all usecases - Both negative and positive tests
#1. Trigger
/**
* #TriggerName : ContactTrigger
* #CreatedBy : Rajesh Kamath
* #CreatedOn : 30-Nov, 2016
* #Description : Trigger to update the image on parent object 'Account' based on the child object 'Contact'
* #LastModified: None
*/
trigger ContactTrigger on Contact(after insert, after update) {
//Instantiate the handler class
ContactTriggerHandler objContactHandler = new ContactTriggerHandler();
/* Trigger Context */
if(Trigger.isAfter) {
//Fire on Insert
if(Trigger.isInsert) {
objContactHandler.onAfterInsert(trigger.new);
}
//Fire on Update
if(Trigger.isUpdate) {
objContactHandler.onAfterUpdate(trigger.new, trigger.oldMap);
}
}
}
#2. Handler
/**
* #HandlerName : ContactTriggerHandler
* #TriggerName : ContactTrigger
* #TestClassName : ContactTriggerHandlerTest [Make sure you create this with the steps at the end of this handler]
* #CreatedBy : Rajesh Kamath
* #CreatedOn : 30-Nov, 2016
* #Description : Trigger to update the image on parent object 'Account' based on the child object 'Contact'
* #LastModified: None
*/
public with sharing class ContactTriggerHandler {
/*
#MethodName : onAfterInsert
#Parameters : List<Contact> lstNewContactRecords
#LastModifiedBy : None [Make sure when anyone updates even this line will be updated for help for other users who work on later phase]
*/
public void onAfterInsert(List<Contact> lstNewContactRecords){
//Call a common method where we have logic
reflectChildImageOnParent(lstNewContactRecords, null);
}
/*
#MethodName : onAfterUpdate
#Parameters : List<Contact> lstContactRecords, Map<Id, Contact> mapOldContactRecords
#LastModifiedBy : None [Make sure when anyone updates even this line will be updated for help for other users who work on later phase]
*/
public void onAfterUpdate(List<Contact> lstContactRecords, Map<Id, Contact> mapOldContactRecords){
//Call a common method where we have logic
reflectChildImageOnParent(lstContactRecords, mapOldContactRecords);
}
/*
#MethodName : reflectChildImageOnParent
#Parameters : List<Contact> lstContactRecords, Map<Id, Contact> mapOldContactRecords
#LastModifiedBy : None [Make sure when anyone updates even this line will be updated for help for other users who work on later phase]
*/
private static void reflectChildImageOnParent(List<Contact> lstContactRecords, Map<Id, Contact> mapOldContactRecords){
/* Local variable declaration */
List<Account> lstAccountsToUpdate = new List<Account>();
for(Contact objContact : lstContactRecords) {
//Execute on insert and update
if((Trigger.isInsert || (Trigger.isUpdate && objContact.Child_Image__c != mapOldContactRecords.get(objContact.Id).Child_Image__c)) && objContact.Account__c != null) {
//List of accounts to update
lstAccountsToUpdate.add(new Account(Id = objContact.Account__c, Parent_Image__c = objContact.Child_Image__c));
}
}
//Update the account records
if(!lstAccountsToUpdate.isEmpty()) {
update lstAccountsToUpdate;
}
}
}
This can be referred for your usecase.
Please mark as 'Best Answer' if this was helpful
loyalty - Child Obj
fields:
lightingdata__Contact__c (relationship)
lightingdata__imagenims__c // Image field
Contact - Parent Obj
field: lightingdata__Imagefromloyalty__c
trigger loyaltytocon on Loyalty__c (after insert, after update) {
Map<id, Contact> conlist;
List<Id> idlist=new List<id>();
for (Loyalty__c loy:trigger.new) {
idlist.add(loy.lightingdata__Contact__c);
}
conlist= new Map<id, contact>([select id, lightingdata__Imagefromloyalty__c from contact where id In : idlist]);
for(Loyalty__c lo:trigger.new){
contact con = conlist.get(lo.lightingdata__Contact__c) ;
system.debug('con data' + con);
con.lightingdata__Imagefromloyalty__c = lo.lightingdata__imagenims__c;
}
update conlist.values();
}
In pareant object field it will return that image filed have URL.
Then you can create one formula filed and just refer (lightingdata__Imagefromloyalty__c) in formul it will display the image.

Apex Trigger to Update Contact from Custom Object

Long story short, I need to update a custom field in my standard Contact, that fires after a different, unrelated Custom Object is updated. I've tried to write a trigger that passes the field value from my Custom Object to the Contact, but I keep getting a variety of errors - the most recent of which has stumped me. The end goal is to update Passing__c from Passing_Field__c.
I'm getting an unexpected Token: "(" error on the for(Contact C: line. It is literally so simple I cannot figure it out.
Here is my code below. I've simplified the naming convention to try and make it more relatable. Any help is appreciated. I'm pretty new to Apex and Triggers, and I've been at this for a couple of hours now, hopefully some advice can send me to 'home plate'.
trigger ContactUpdater on Custom_Object_Name__c (after update) {
List<Contact> updatedContacts = new List<Contact>();
Set<Id> ObjectIds = new Set<Id>();
Set<String> ObjectCont = new Set<String>();
Set<Boolean> ObjectActive = new Set<Boolean>();
Set<String> ObjectPass = new Set<String>();
for(Custom_Object_Name__c p : trigger.new)
{
If(p.Active__c == true){
ObjectIds.add(p.Id);
ObjectCont.add(p.Contact__c);
ObjectActive.add(p.Active__c);
ObjectPass.add(p.Passing_Field__c);
}
try{ for(Contact c : [SELECT Id, Passing__c FROM Contact WHERE (AccountId IN (Select Account__c from Custom_Object_Name__c )) AND ObjectActive = true])
{
set(c.Passing__c = p.Passing_Field__c);
c.FieldToUpdate = c.Passing__c;
updatedContacts.add(c);
}
update updatedContacts;
}
catch(exception e){
throw e;
}
}
}
Notes: Active__c is a checkbox. Passing__c and Passing_Field__c are both text boxes.
I believe the issue is in the WHERE clause of your SOQL query:
WHERE (AccountId = (Select Account__c from Custom_Object_Name__c ))
Salesforce is expecting you to compare AccountId to an Id of some sort, rather than the results of some subquery. You probably want to try something like:
WHERE (AccountId in (Select Account__c from Custom_Object_Name__c))

Apex Trigger Works, can not get test pass

I came back to this 3 hours later and with no changes to any code, test execution worked.
Disregard This Question
I have written a trigger that works great for setting the accountID on a contact record based on an external ID.
I had a test that worked great, but I added some logic to the trigger so it only updates contacts with a 'Default Account' as account. Now my test fails saying it did not update the account even though it still works as designed when saving records.
What am I missing?
I added line 4
ID DefaultAccID = [select ID from Account where Name = 'Default Account'].ID;
and the if around line 9
if (contactNew.AccountID == DefaultAccID) {
}
to Trigger:
trigger TRG_Contact_SetHouseholdID on Contact (before update, before insert) {
Set<String> AccIDlist = new Set<String>();
ID DefaultAccID = [select ID from Account where Name = 'Default Account'].ID;
// loop through records finding thoes that need to be linked
for(Contact contactNew:Trigger.New){
if (contactNew.AccountID == DefaultAccID) {
AccIDlist.add(contactNew.RPHouseholdID__c);
}
}
Map<String, ID> AccountMap = new Map<String, ID>();
//loop needing linked and get account ID if it exist
for(Account oneAccount:[SELECT RPHouseholdID__c, ID from Account where RPHouseholdID__c IN :AccIDlist]){
AccountMap.put(oneAccount.RPHouseholdID__c, oneAccount.ID);
}
// loop through records updating the ones that need link
for(Contact contactNew:Trigger.New){
if (AccountMap.get(contactNew.RPHouseholdID__c) <> null){
contactNew.AccountID = AccountMap.get(contactNew.RPHouseholdID__c);
}
}
}
Test Class:
#isTest
Private class TRG_Contact_SetHouseholdID_Test {
static TestMethod void Test0_TestInsertWithValue(){
insertTestAccounts();
Account defaultAccount = [select ID from Account where name = 'Default Account' limit 1];
Account newAccount = [select ID from Account where name = 'Camper Family' limit 1];
test.startTest();
insertTestContact(defaultAccount.ID);
test.stopTest();
Contact newContact = [select ID,AccountID from Contact where firstname = 'Happy' and lastname = 'Camper' limit 1];
System.assertEquals(newContact.AccountID, newAccount.ID, 'accountID did not get changed from default (' + defaultAccount.ID + ')');
}
private static void insertTestAccounts()
{
Account obj = new Account();
obj.Name = 'Default Account';
insert obj;
obj = new Account() ;
obj.Name = 'Camper Family';
obj.RPHouseholdID__c = '111';
insert obj;
}
private static void insertTestContact(ID defaultID)
{
Contact obj = new Contact();
obj.AccountID = defaultID;
obj.firstName = 'Happy';
obj.lastname = 'Camper';
obj.RPHouseholdID__c = '111';
insert obj;
}
}
Expanding a bit on #zachelrath 's answer, beginning with API version 24.0, test methods are isolated from the data in the organization (with a few exceptions User, RecordType, etc. see here for the full list). Rather than changing the API version of the file, the easiest thing to do is to add the see all data directive to the isTest annotation, like so:
#isTest(SeeAllData=true)
Private class TRG_Contact_SetHouseholdID_Test {
// etc
Set your test class' API version to 24.0 --- I'd bet your initial query for the Default Account is pulling in a preexisting record whose Name is 'Default Account', instead of the Default Account you're creating in your test data. There are 2 ways to get around this:
(Easiest) Change your test class to API version 24.0
If you would rather stay in API 23.0 or lower, then, at the start of your test method, delete all accounts named 'Default Account', then insert your test accounts.