You need to sign in to do that
Don't have an account?
Everton CP7
Test Class for Trigger
I'm brand new to Apex and need to test triggers to deploy to production.
I became reading some topics and I tried a lot do this test class for my trigger, but none doesn't work.
Anyone could help me with this test class?
Code:
trigger EmailTarefa on Task (after update) { static final String SUBJECT = 'Tarefa Concluída'; static final String BODY = 'Atribuido Para: {0}\nRelativo a: {1}\nStatus: {2}\nAssunto: {3}\nComentário Enviado: {4}\nComentário de Conclusão: {5}'; List<Id> creatorIds = new List<Id>(); List<Id> ownerIds = new List<Id>(); for (Task task : Trigger.new) { if (task.Status == 'Concluído') { creatorIds.add(task.CreatedById); ownerIds.add(task.OwnerId); } } List<User> creators = [Select Id, Email from User Where Id in :creatorIds]; Map<Id,String> creatorIdsToEmails = new Map<Id,String>(); for (User creator : creators) { creatorIdsToEmails.put(creator.Id,creator.Email); } List<User> owners = [Select Id, FirstName, LastName From User Where Id in :ownerIds]; Map<Id,String> ownerIdsToNames = new Map<Id,String>(); for (User owner : owners) { ownerIdsToNames.put(owner.Id,owner.FirstName + ' ' + owner.LastName); } for (Task task : Trigger.new) { if (task.Status == 'Concluído') { try { Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); mail.setToAddresses(new String[] {creatorIdsToEmails.get(task.CreatedById)}); mail.setSubject(SUBJECT); String url = System.URL.getSalesforceBaseUrl().toExternalForm() + '/' + task.WhatId; mail.setPlainTextBody(String.format(BODY,new String[]{ ownerIdsToNames.get(task.OwnerId), url, task.Status, task.Subject, task.Description, task.Coment_rio_de_conclus_o_de_tarefa__c })); Messaging.SendEmailResult[] result = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail}); if (!result[0].isSuccess()) { System.debug(LoggingLevel.ERROR, 'Failed to send email'+result[0].getErrors()[0].getMessage()); } } catch (System.EmailException ex) { System.debug(LoggingLevel.ERROR, 'Encountered EmailException'); } } } }
Any help in this will be realy apreciated.
Thanks!
Hi Everton,
Try below code :-
@IsTest(SeeAllData=true)
publc class EmailTarefa_test{
static testmethod void MyUnitTest(){
User u = [select id from User where name='<some username in your org>'];
Task tsk = new Task(Status='Not Started',Subject='Call',Priority='Normal',OwnerId=u.id);
insert tsk;
tsk.Status = 'Concluído';
update tsk;
}
}
All Answers
Your test class needs to create a set of test data that causes the trigger to fire.
Create a task:
Task t = new Task(Subject= 'First Subject');
insert t;
t.Subject = 'Second Subject';
upldate t;
That code will cause any "After Update" trigger to fire. (It creates a task, then updates it- It would also cause a before/after insert trigger to fire)
Thanks Tanyril !
I just have to put this code?
I'm sorry. Can you be more specific?
I've never done a test class that actually worked..
You have to create a class.
Here's a test class I wrote to test a trigger that fires an e-mail off to some of my users- Feel free to use it as an example:
You can pretty much copy and paste this, replacing anything wrapped in ##
@isTest
private
class ##ENTERCLASSNAME## {
static testMethod void ##NAMEOFTESTMETHOD##() {
Task t = new Task(Subject= 'First Subject');
insert t;
t.Subject = 'Second Subject';
update t;
}
You can create a single test class that essentially could test any and all situations by creating an instance of each object in salesforce, then updating, deleting and undeleteing each of them
Hi Everton,
Try below code :-
@IsTest(SeeAllData=true)
publc class EmailTarefa_test{
static testmethod void MyUnitTest(){
User u = [select id from User where name='<some username in your org>'];
Task tsk = new Task(Status='Not Started',Subject='Call',Priority='Normal',OwnerId=u.id);
insert tsk;
tsk.Status = 'Concluído';
update tsk;
}
}
Out of curiosity- Why use the SeeAllData instead of just creating a test instance of a user?
If you have seen,I am querying on User object and to get the record,I have to use (seeAllData=true) in your code.
Thanks both for helping me.
So, I had already tried exactly this Tanyril.
When I will deploy to production still fails.
I tried now your code Vinit and works perfectly.
Can you explain some stuffs?
I put this:
I was thinking this will only work if the user "Marketing" is creating or is the owner's task.
And this will only work if the status="não iniciado".
But I don't have to use this status and don't have to be the user "Marketing". And this is exactly what I need.
I just want understand the code.
Thank you so much Vinit and Tanyril !!!!
The basic purpose of creating Test class is to get code coverage and these data is not committed in your org as the data is used only in the test class.
So,whether you are a Marketing User or not that is not required because we need to get a user id from your Org to populate the OwnerId of Task as this is required field to insert a task because OwnerId is a mandatory field.
and the same goes with Status field we need to populate it as to insert a task record.
Also, as in your Trigger if Status = 'Concluído',hence I used the same in my Test class so that the Trigger executes and works.
Hope this helps!!