How to write testcase for trigger? - salesforce

I have a trigger which copies the billing street address from the related Account to the other streets address on the related Contact. I wrote this trigger from reading materials online is this correct? Is there better way to write it?
Public class iTestClass {
public static testmethod void test()
{
Contact objContact1;
Contact objContact2;
objContact1 = New Contact();
objContact1.OtherStreet = '123 lane';
objContact1.OtherCity = 'Washington';
objContact1.OtherState = 'OR';
objContact1.OtherCountry = 'USA';
objContact1.OtherPostalCode = '12122';
objContact2 = New Contact();
objContact2.OtherStreet = '232 st.';
objContact2.OtherCity = 'cleveland';
objContact2.OtherState = 'OH';
objContact2.OtherCountry = 'USA';
objContact2.OtherPostalCode = '166030';
}
}

You're on the right lines, but a) you're not inserting the contact records, and b) you need to insert an account first, then set the account ID on those contacts before you insert them.
// before creating the contacts create an account
Account sAcct = new Account();
sAcct.Name = 'Test Account';
sAcct.BillingStreet = '1 Some Street'; // I forget the name of the field!
// etc.
insert sAcct;
// then on your contacts do this:
objContact1.Account = sAcct.Id;
// then insert them at the end to fire the trigger
insert objContact1;

Related

How To Understand #TestClass Apex code with List embedded in Map

I am trying to understand this code ,this seems to be a test class,but i am having hard time to understand the code,i know conceptually how List and Map collection works in Sales force,but this seems to be little difficult to understand,
.In brief to me this seems to test a method which browses a list of CollaborationGroupMember.
For that, CollaborationGroup has been created and code tried to add one User.
can some one please take some time to make me understand the below code line by line?
Thanks in advance
#isTest
public class TestGroupFactory {
public static Map<CollaborationGroup, List<CollaborationGroupMember>> groupWithMember() {
CollaborationGroup groupe = new CollaborationGroup(Name = 'Test1', CollaborationType = 'Public');
insert groupe;
groupe = [SELECT Id, Name FROM CollaborationGroup WHERE Name = 'Test1'];
List<User> users = [SELECT Id, Name, Numero_de_plaque__c, SenderEmail
FROM User
WHERE Name = 'User User'];
List<CollaborationGroupMember> cgms = new List<CollaborationGroupMember>();
for (User u : users) {
CollaborationGroupMember cgm = new CollaborationGroupMember();
cgm.CollaborationGroupId = groupe.Id;
cgm.MemberId = u.Id;
cgms.add(cgm);
}
insert cgms;
return new Map<CollaborationGroup, List<CollaborationGroupMember>>{groupe => cgms};
}
}
It is technically a test class, but it does not perform any tests. Its purpose is to create test data for other test classes that contain test methods. The reason it has the #isTest annotation is so that it is only accessible in test context and does not count against the total test coverage of the organization.
The method shown creates a Chatter Group and adds Users to the group if they have the name "User User".
The code below inserts the Chatter Group and then retrieves it so the Id is available. I don't think the retrieval is necessary in this instance, but I'd have to test it.
CollaborationGroup groupe = new CollaborationGroup(Name = 'Test1', CollaborationType = 'Public');
insert groupe;
groupe = [SELECT Id, Name FROM CollaborationGroup WHERE Name = 'Test1'];
The next section retrieves the Users (presumably created in another test class)
List<User> users = [SELECT Id, Name, Numero_de_plaque__c, SenderEmail
FROM User
WHERE Name = 'User User'];
Then, a list of CollaborationGroupMembers is instantiated. A loop begins that iterates over every User. For each user, a new CollaborationGroupMember is instantiated and added to the list.
List<CollaborationGroupMember> cgms = new List<CollaborationGroupMember>();
for (User u : users) {
CollaborationGroupMember cgm = new CollaborationGroupMember();
cgm.CollaborationGroupId = groupe.Id;
cgm.MemberId = u.Id;
cgms.add(cgm);
}
The group members are inserted
insert cgms;
The group and group members are added to a map and returned
return new Map<CollaborationGroup, List<CollaborationGroupMember>>{groupe => cgms};

How to get the code coverage required to deploy Apex Class

Please Help!!!
I have this Apex controller class that I'm trying to deploy from Salesforce Sandbox to Production but I'm not getting the code coverage required!!
the class is consuming 3 objects, one is stranded and 2 are custom and constructing a hierarchy tree view for those three objects.
//Apex Class
public class TeeView {
/* Wrapper class to contain the nodes and their children */
public class cNodes
{
Public StandardObject gparent {get;set;}
public List<CustomObject1__c> parent {get; set;}
Public List<CustomObject2__c> child {get;set;}
public cNodes(StandardObject gp, List<CustomObject1__c> p, List<CustomObject2__c> c)
{
parent = p;
gparent = gp;
child = c;
}
}
/* end of Wrapper class */
Public List<cNodes> hierarchy;
Public List<cNodes> getmainnodes()
{
hierarchy = new List<cNodes>();
List<StandardObject> tempparent = [Select Id,Name , End_Date__c, Owner.Name Account.Name from Contract ];
for (Integer i =0; i< tempparent.size() ; i++)
{
List<CustomObject1__c> tempchildren = [Select Id,Name, Owner.Name , (select Id,Name, Owner.Name from CustomObject2__r) from CustomObject1__c where Related_Field__c = :tempparent[i].Id];
List<CustomObject2__c> tempchild = [Select Id,Name Owner.Name from CustomObject2__c where Related_Field__c= :tempparent[i].Id];
hierarchy.add(new cNodes(tempparent[i],tempchildren, tempchild));
}
return hierarchy;
}
}
//Test Class
#isTest
public class treeviewTest
{
static testMethod void test1()
{
test.startTest();
Account acc = new Account(Name = 'Unit test account');
insert acc;
StandardObject c = new StandardObject(
Name = 'test',
AccountId = acc.Id,
Status = 'Draft',
StartDate = System.today());
try
{
insert c;
}
catch (Exception ex)
{
ApexPages.addMessages(ex);
}
List<StandardObject> standard = [select Id, Name from StandardObject where Name = 'test'];
system.assertequals(standard.size(), 1);
CustomObject1__c s = new CustomObject1__c(
Related_StandardObjectField__c = c.Id,
Name = 'test'
);
try
{
insert s;
}
catch (Exception ex)
{
ApexPages.addMessages(ex);
}
List<CustomObject1__c> cus1 = [select Id, Name from CustomObject1__c where Name = 'test'];
system.assertequals(cus1.size(), 1);
insert new CustomObject2__c(Related_StandardObjectField__c = c.Id, Description__c = 'test');
List<CustomObject2__c> cus2 = [select Id, Name from CustomObject2__c where Description__c = 'test'];
system.assertequals(cus2.size(), 1);
insert new CustomObject2__c(Related_CustomObject1Field__c = s.Id, Description__c = 'test');
List<Mods__c> cus3 = [select Id, Name from Mods__c where Description__c = 'test'];
system.assertequals(cus3.size(), 1);
treeView view = new treeView();
view.getmainnodes();
test.stopTest();
}
}
Oh man, where do we even start... Looks like you copy-pasted some code at random trying to get the test to work? Your code works on Contract, CustomObject1__c, CustomObject2__c. Your unit test inserts Contract, Subaward__c, Mods__c. Was this some attempt at anonymizing your code? And what's this List<StandardObject> thing, it shouldn't even compile.
I think you need help of a developer with more experience, you've cobbled something together but it doesn't follow the Salesforce best practices for code...
About the main class
Smart use of subqueries will mean
you waste less SOQL (it's bad idea to blindly select all records without any filters but whatever),
don't run into errors related to "too many SOQL statements" (the limit is 100 so since you query in a loop - your code will crash and burn the moment you have around 50 Contracts)
lead to compact code occupying less lines (easier to maintain & cover with tests).
I'd go with something like that, query Contract & first related list in one go and then the parents + children in another query. Using a Map to link them for displaying.
List<Contract> levelOneAndTwo = [SELECT Id, Name, End_Date__c, Owner.Name, Account.Name,
(SELECT Id,Name, Owner.Name FROM Subawards__r)
FROM Contract];
Map<Id, SubAward__c> levelTwoAndThree = new Map<Id, Subaward__c>([SELECT Id,
(SELECT Id,Name Owner.Name FROM Mods__r)
FROM Subaward__c WHERE Contract__c = :levelOneAndTwo];
);
This wastes only 2 queries but fetches all contracts and their related data. Then you can loop over results building your wrapper object or just feed it directly to Visualforce for displaying.
About the unit test
You don't get the coverage because you're spread too thin. One unit test methods inserts only Contracts (so your main query will hit something, give you some coverage). Then another method (in completely different context) inserts some child objects - but they don't matter. In that other method there are 0 contracts so it won't even enter your main loop. Combine it into one?
Account acc = new Account(Name = 'Unit test account');
insert acc;
Contract c = new Contract(
Name = 'test contract',
AccountId = acc.Id,
Status = 'Draft',
StartDate = System.today()
);
insert c;
Subaward__c s = new Subaward(
Contract__c = c.Id,
Name = 'test'
);
insert s;
insert new Mod__c(Subaward__c = c.Id, Description__c = 'test');
Now you have nice tree hierarchy set up, from Account all the way down. Queries in the test should hit some data.
I was finally able to get %100 code coverage for the above class by adding these lines to the test class:
treeView view = new treeView();
view.getmainnodes();
system.assert(view.hierarchy.size() > 0);

How do I write a test class for Messaging.SingleEmailMessage apex class?

I have written the below Apex class that processes incoming email that are sent to an email service address and creates a new task from the incoming mail and then associates this new task with a matching record in salesforce. The match is done on the record name and incoming email subject. The class also sends an email notifying the "Assigned to" user that they have received a reply on a request they are working on.
This works perfect in Sandbox but I have no experience writing test classes. Can anyone advise how I write the test class for the below?
global class RequestEmailHandler implements Messaging.InboundEmailHandler {
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
String myPlainText = email.plainTextBody;
String subject = email.fromName + ' - ' + email.subject;
system.debug(email);
subject = subject.left(255);
Request__c request;
if (subject != null && subject.trim().length() > 0 && subject.indexOf('(R-') > 0) {
Integer idx = subject.indexOf('(R-');
String requestName = subject.substring(idx+1, subject.indexOf(')', idx));
request = [SELECT Id, Assigned_To__c FROM Request__c WHERE Name = :requestName];
}
if (request == null) {
result.message = 'We were unable to locate the associated request.This may be due to the unique "R" number being removed from the subject line.\n Please include the original email subject when replying to any emails.';
result.success = false;
return result;
}
// Add the email plain text into the local variable
Task task = new Task(
WhatId = request.Id,
Description = myPlainText,
Priority = 'Normal',
Status = 'Completed',
Type = 'Email',
Subject = subject,
ActivityDate = System.today(),
RecordTypeId = '01250000000HkEw');
insert task;
//Find the template
EmailTemplate theTemplate = [select id, name from EmailTemplate where DeveloperName = 'New_Email_Reply2'];
//Create a new email right after the task
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
//Add email To addresses to list
List<String> toAddresses = new List<String>();
toAddresses.add(email.fromAddress);
//Set the list of to addresses
mail.setToAddresses(toAddresses);
//Set the template id
mail.setTemplateId(theTemplate.id);
//The Id of the user
mail.setTargetObjectId(request.Assigned_To__c);
//Set the id of the request
mail.setWhatId(request.Id);
//If you need the email also saved as an activity, otherwise set to false
mail.setSaveAsActivity(false);
//Send Email
try {
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
}
catch (EmailException e) {
system.debug('sendEmail error: ' + e.getMessage());
}
// Save attachments, if any
if (email.textAttachments != null)
{
for(Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments)
{
Attachment attachment = new Attachment();
attachment.Name = tAttachment.fileName;
attachment.Body = Blob.valueOf(tAttachment.body);
attachment.ParentId = request.Id;
insert attachment;
}
}
//Save any Binary Attachment
if (email.binaryAttachments != null)
{
for(Messaging.Inboundemail.BinaryAttachment bAttachment : email.binaryAttachments) {
Attachment attachment = new Attachment();
attachment.Name = bAttachment.fileName;
attachment.Body = bAttachment.body;
attachment.ParentId = request.Id;
insert attachment;
return result;
}
}
return result;
}
}
Below is my attempt which is only getting 24% coverage. I know it is missing vital code but I do not know enough about test classes to take it any further.
Can anyone assist?
Test Class
#isTest
public class testforemail {
static testMethod void insertRequest() {
Request__c requestToCreate = new Request__c();
requestToCreate.Subject__c= 'test';
requestToCreate.Requested_By_Email__c= 'graham.milne#fmr.com';
insert requestToCreate;
Messaging.InboundEmail email = new Messaging.InboundEmail();
Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
Request__c testRequest = [select Id,Name from Request__c limit 1];
System.debug(testRequest.Name);
email.subject = (testRequest.Name);
email.fromName = 'test test';
email.plainTextBody = 'Hello, this a test email body. for testing purposes only.Phone:123456 Bye';
Messaging.InboundEmail.BinaryAttachment[] binaryAttachments = new Messaging.InboundEmail.BinaryAttachment[1];
Messaging.InboundEmail.BinaryAttachment binaryAttachment = new Messaging.InboundEmail.BinaryAttachment();
binaryAttachment.Filename = 'test.txt';
String algorithmName = 'HMacSHA1';
Blob b = Crypto.generateMac(algorithmName, Blob.valueOf('test'),
Blob.valueOf('test_key'));
binaryAttachment.Body = b;
binaryAttachments[0] = binaryAttachment ;
email.binaryAttachments = binaryAttachments ;
envelope.fromAddress = 'user#fmr.com';
// Add the email plain text into the local variable
Task task = new Task(
WhatId = (testRequest.Id),
Description = email.plainTextBody,
Priority = 'Normal',
Status = 'Completed',
Type = 'Email',
Subject = (testRequest.Name),
ActivityDate = System.today(),
RecordTypeId = '01250000000HkEw');
insert task;
// setup controller object
RequestEmailHandler catcher = new RequestEmailHandler();
Messaging.InboundEmailResult result = catcher.handleInboundEmail(email, envelope);
System.assertEquals( true,result.success );
}
}
The first step is to identify what lines of code are not being covered by your test class.
If you're using Eclipse, you can see this from the Apex Test Runner View.
Or, you can see this from the Developer console as well.
Another thing you need to consider is the isolation of your DML operations in a separate utility class.
public class TestUtils
{
// create request objects method here
// create task objects method here
}
Also, check your debug logs and make sure your code is not throwing any exceptions (i.e., null pointer exceptions, DML exceptions, etc.)
You must also add assertions to check that your code is behaving as expected.
Hope this helps.
The main thing you need to do is to test as many use cases as you can via unit tests.
So, setup data for specific case and run you email processing. After email, check the result using System.assertEquals(). Make separate tests for each use case.
Then, if you don't hit at least 75%, check what is not covered. You, probably, either don't need that code (in case you covered all use cases), or don't write a test for use case, which uses those lines of code.

Salesforce Apex - Existing Contact used to create new lead

I would like to create after update APEX for salesforce that can take a contact and recreate it as a Lead when a field on the contact is checked true. Any help would be appreciated.
Yeah so I think i need to make a list of the contacts that need to be moved into the lead. I'm forgetting the format to grab the fields from the contact so i can map them into the lead.
public void createLead_Update(List<Contact> oldContacts, List<Contact> newContacts) {
System.debug('createLead_Update: entering trigger');
List<ID> createNewLead = new List<ID>();
Lead lead = new Lead();
Contact aContact = newContacts[i];
for (integer i=0; i<newContacts.size(); i++) {
// find contacts where the create lead checkbox is checked.
// on update, we care if the value is changed
Contact newValues = newContacts[i];
Contact oldValues = oldContacts[i];
if (newValues.createlead__c != oldValues.createlead__c) {
createNewLead.add(new Lead(
lead.firstName = aContact.firstName));
}
insert new lead
}
System.debug('createLead_Update: exiting trigger');
}
List<Lead> newLeadsList= new List<Lead>();
for (integer i=0; i<newContacts.size(); i++) {
if (newContacts[i].createlead__c != oldContacts[i].createlead__c && newContacts[i].createlead__c ) {
newLeadsList.add(new Lead(lead.firstName = newContacts[i].firstName));
}
}
insert newLeadsList;

FIELD_CUSTOM_VALIDATION_EXCEPTION

I am writing a test class for a trigger. But i am not able to run it properly it only contain 68%.
The error is
System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, This part is not forecastable.
#isTest
private class TestTriggers
{
static testMethod void testService()
{
//Insert part
list<Opportunity> Opportunity = new list<Opportunity>();
Opportunity = [Select id from Opportunity];
list<Product2> Product = new list<Product2>();
Product = [Select id from Product2];
Part__c p = new Part__c(Stage__c = 'idea',Product__c=Product[0].id,Opportunity__c=Opportunity[0].id);
insert p;
//Update part
list<part__c> partlist = new list<part__c>();
partlist = [Select Stage__c from part__c where Stage__c = 'idea'];
partlist[0].Stage__c = 'update';
update partlist;/* */
}
}
thanks
Anuraj
There is a validation rule on the Part object. To view the validation rule(s), go to Setup > Create > Objects > Part > Validation Rules.
You'll need to modify your code to create a Part__c record that complies with the validation rules.

Resources