function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Christian ØelundChristian Øelund 

Test class help for triggers

Hey I'm really new to Salesforce development. I have two triggers i need to deploy from sandbox, but code coverage is 0%.
I have to add some test classes, right? but i'm not sure how to handle it.

Trigger 1
trigger CopyPartnerSource on Lead (before insert, before update) {

for (Lead l : Trigger.new) { l.Partner_Account_Mirror__c = l.Partner_Account__c; } }




Trigger 2
trigger Trigger_Task_Send_Email on Task (before update) {
  
    Set<Id> createdbyIds = new Set<Id>();
   
    for(Task tsk: Trigger.New)
        createdbyIds.add(tsk.createdbyId);
   
    Map<Id, User> userMap = new Map<Id,User>([select Name, Email from User where Id in :createdbyIds]);
    for(Task tsk : Trigger.New)
    {
        User theUser = userMap.get(tsk.createdbyId);
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {theUser.Email};
        mail.setToAddresses(toAddresses);    // Set the TO addresses
        mail.setSubject('A task created by you has been updated');    // Set the subject
  
        String template = 'Hello {0}, \nYour task has been modified. Here are the details: \n\n';
        template+= 'Subject - {1}\n';
        template+= 'Due Date - {2}\n';
        String duedate = '';
        if (tsk.ActivityDate==null)
            duedate = '';
        else
            duedate = tsk.ActivityDate.format();
        List<String> args = new List<String>();
        args.add(theUser.Name);
        args.add(tsk.Subject);
        args.add(duedate);
        
       
        // Here's the String.format() call.
        String formattedHtml = String.format(template, args);
       
        mail.setPlainTextBody(formattedHtml);
        Messaging.SendEmail(new Messaging.SingleEmailMessage[] {mail});
    }
}




Any help will be appreciated, thanks
Best Answer chosen by Christian Øelund
pconpcon
I'm not saying you should use his test code, but this should compile for you
 
@isTest
private class Trigger_Task_Send_EmailTest {
    static testMethod void Trigger_Task_Send() {
        test.StartTest();

        List<Lead> lstLead = new List<Lead>();
        for (Integer i = 1 ; i<=10 ;i++) {	
            lstLead.add(new Lead(
                FirstName='Test'+i,
                LastName = 'UnitTest',
                Company = 'Test Company',
                LeadSource = 'Test Leadsource'
            ));
        }	

        insert lstLead;

        Lead testLead = lstLead.get(0);
        testLead.FirstName= 'Test name';
        update testLead;
			
        System.assertEquals(10, lstLead.size()) ;
			
        test.stopTest();
    }
}

 

All Answers

pconpcon
Welcome to the wonderful world of Salesforce!  The first trigger you have will be pretty easy to test and you'll just want to confirm that the Partner_Account_Mirror__c field is set correctly.  The second trigger is a bit tougher since there is no real way to test that you actually sent out emails.  You can call the Limits class and check the number of email invocations [1] to ensure that the expected number have been sent.  The only problem with this is that you may have other WFR or code that send email and they may skew your testing.

I would recommend reading over the following pages to help you get started with how to write your tests.  Since covering how exactly to write all the tests to cover this is not something people on these boards will do, if you have an specific questions about your tests please feel free to ask those.
[1] https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_limits.htm#apex_System_Limits_getEmailInvocations
Amit Chaudhary 8Amit Chaudhary 8
Please try below test classes :-
@isTest
private class Trigger_Task_Send_EmailTest {
    static testMethod void Trigger_Task_Send()
	{

		test.StartTest();
       
       Lead testLead = new Lead(
       FirstName='Demo 100800',
       LastName = 'Demo 100800 UnitTest',
       Company = 'Test Company',
       LeadSource = 'Test Leadsource',
       );
       insert testLead;

	   testLead.FirstName= 'Test';
		update testLead;
       
       test.stopTest();
    }
}

Please let us know if above test class will help you
pconpcon
While Amit's code may cause you to reach enough code coverage to deploy it is not a good test.  His test is not broken into parts for both insert and update, it does not include any asserts of any kind.  Because of this, I would not recommend that you use that test code.
Amit Chaudhary 8Amit Chaudhary 8
Thanks Pcon for your valuable comment i agree with you.

Hi Christian Øelund,

Please try below code :-
@isTest
private class Trigger_Task_Send_EmailTest {
    static testMethod void Trigger_Task_Send()
	{
		test.StartTest();
			List<Lead> lstLead = new List<Lead>();
			for(Integer i = 1 ; i<=10 ;i++)
			{	
				Lead testLead = new Lead(
				FirstName='Test'+i,
				LastName = 'UnitTest',
				Company = 'Test Company',
				LeadSource = 'Test Leadsource',
				);
				lstLead.add(testLead);
			}	
			insert lstLead;
			Lead testLead = lstLead[0];
			testLead.FirstName= 'Test name';
			update testLead;
			
			System.assertEquals(10, lstLead.size())
			
		test.stopTest();
    }
}

Please let us know if above test class will help you
Christian ØelundChristian Øelund
Thanks both of you. pcon I will go trough your links as soon as posible, really nice of you.

Amit;
How do I deal with this error then.
Compile Error: unexpected token: ')' at line 14 column 16 (Do I have to write some more?)
Amit Chaudhary 8Amit Chaudhary 8
Try below code :-
@isTest
private class Trigger_Task_Send_EmailTest {
    static testMethod void Trigger_Task_Send()
	{
		test.StartTest();
			List<Lead> lstLead = new List<Lead>();
			for(Integer i = 1 ; i<=10 ;i++)
			{	
				Lead testLead = new Lead(
				FirstName='Test'+i,
				LastName = 'UnitTest',
				Company = 'Test Company',
				LeadSource = 'Test Leadsource'
				);
				lstLead.add(testLead);
			}	
			insert lstLead;
			Lead testLead = lstLead[0];
			testLead.FirstName= 'Test name';
			update testLead;
			
			System.assertEquals(10, lstLead.size())
			
		test.stopTest();
    }
}

 
Christian ØelundChristian Øelund
Thank you for your time. And sorry for my newbee skills. I think it's getting closer, but now it says Compile Error: expecting a semi-colon, found 'test.stopTest' at line 24 column 8

I tried put in the semicolon and made it posible to save the test, but my code coverage is still 0% for my Trigger_Task_Send_Email.
Christian ØelundChristian Øelund
Still make that error, it's driving me nuts. :(
 
Christian ØelundChristian Øelund
Error: Compile Error: unexpected token: ')' at line 14 column 16
pconpcon
I'm not saying you should use his test code, but this should compile for you
 
@isTest
private class Trigger_Task_Send_EmailTest {
    static testMethod void Trigger_Task_Send() {
        test.StartTest();

        List<Lead> lstLead = new List<Lead>();
        for (Integer i = 1 ; i<=10 ;i++) {	
            lstLead.add(new Lead(
                FirstName='Test'+i,
                LastName = 'UnitTest',
                Company = 'Test Company',
                LeadSource = 'Test Leadsource'
            ));
        }	

        insert lstLead;

        Lead testLead = lstLead.get(0);
        testLead.FirstName= 'Test name';
        update testLead;
			
        System.assertEquals(10, lstLead.size()) ;
			
        test.stopTest();
    }
}

 
This was selected as the best answer
Amit Chaudhary 8Amit Chaudhary 8
Sorry Christian Øelund,

I was forget to remove , from
LeadSource = 'Test Leadsource',

Please try below code :-
@isTest
private class Trigger_Task_Send_EmailTest {
    static testMethod void Trigger_Task_Send()
	{
		test.StartTest();
			List<Lead> lstLead = new List<Lead>();
			for(Integer i = 1 ; i<=10 ;i++)
			{	
				Lead testLead = new Lead(
				FirstName='Test'+i,
				LastName = 'UnitTest',
				Company = 'Test Company',
				LeadSource = 'Test Leadsource'
				);
				lstLead.add(testLead);
			}	
			insert lstLead;
			Lead testLead = lstLead[0];
			testLead.FirstName= 'Test name';
			update testLead;
			System.assertEquals(10, lstLead.size());
		test.stopTest();
    }
}

Plese let us know if this will help you.
Christian ØelundChristian Øelund
User-added image
Thanks both of you. But should'nt the code coverage go up, when you deploy the test class? 

First time working in this :(

 
pconpcon
You also have to run the test class.  Just doing the deploy won't cause the tests to run.
Christian ØelundChristian Øelund
Thanks
 
Christian ØelundChristian Øelund
I had run the test, but code coverage is still 0% :( 
pconpcon
Ah, the reason why that class is not getting any coverage is your test class is only on the Lead object.  You'll need to create another test class that inserts Leads that meet your criteria in your other trigger.
Christian ØelundChristian Øelund
Thanks pcon
It's starting to get difficult when I'm not into coding. I tried a lot of methods like this;
@isTest
private class UnitTest1 {
    static testMethod void Trigger_Task_Send() {
 
   
    Lead l = new Lead(Company = 'Test Lead',
                FirstName='Test'+i,
                LastName = 'UnitTest',
                Company = 'Test Company',
                LeadSource = 'Test Leadsource'
    insert l;
    }
}

But still, cant make a test class that inserts leads. :(
pconpcon
This is because your Task trigger is on update and your test code is only inserting
 
@isTest
private class Trigger_Task_Send_Email_Test {
    static testMethod void emailTest_single() {
        Task testTask = new Task(
            Subject = 'Test Task 1',
            ActivityDate = Date.today()
        );
        insert testTask;

        Integer emailsSentPre = Limits.getEmailInvocations();

        Test.startTest();

        testTask.Subject = 'Test Task 2';
        update testLead;

        Test.stopTest();

        Integer emailsSentPost = Limits.getEmailInvocations();
        Integer emailsSent = emailsSentPost - emailsSentPre;

        System.assertEquals(1, emailsSet, 'We should have only sent one email');
    }
}

NOTE: This code has not been tested and may contain typographical or logical errors

This test is for a single email invocation.  I would then take this formula and repeat for bulk update of Leads.  To get 100% coverage you should also make sure you are updating a task to have an ActivityDate of null.

Also, while I'm doing it.  This is a better test for your Lead trigger
 
@isTest
private class CopyPartnerSource_Test {
    static testMethod void CopyPartnerSourceTest() {
        Account testAccount = new Account(
            Name = 'Test Account'
        );
        insert testAccount;

        Lead testLead = new Lead(
            FirstName='Test Lead 1',
            LastName = 'UnitTest',
            Company = 'Test Company',
            LeadSource = 'Test Leadsource',
            Partner_Account__c = testAccount.Id
        );

        Test.startTest();

        insert testLead;

        Test.stopTest();

        testLead = [
            select Partner_Account_Mirror__c
            from Lead
            where Id = :testLead.Id
        ];

        System.assertEquals(
            testAccount.Id,
            testLead.Partner_Account_Mirror__c,
            'The partner account was not mirrored correctly'
        );
    }
}
Christian ØelundChristian Øelund
Thanks a lot. Got 96% code coverage. Case closed.
Christian ØelundChristian Øelund
Thanks again pcon

I've tried to correct the class, so it looks like this;
@isTest
private class Trigger_Task_Send_Email_Test1 {
    static testMethod void emailTest_single() {
        Task testTask = new Task(
            Subject = 'Test Task 1',
            ActivityDate = Date.today()
        );
        insert testTask;

        Integer emailsSentPre = Limits.getEmailInvocations();

        Test.startTest();

        testTask.Subject = 'Test Task 2';
        update testTask;

        Test.stopTest();

        Integer emailsSentPost = Limits.getEmailInvocations();
        Integer emailsSent = emailsSentPost - emailsSentPre;

        System.assertEquals(1, emailsSent, 'We should have only sent one email');
    }
}

It gived me code coverage of 96% but makes these errors, so still cant's but in production.


<span unselectable="on" "="" style="display: block; padding: 3px 4px; overflow: hidden; margin-left: 0px; color: rgb(34, 34, 34); font-family: Arial, Helvetica, sans-serif; font-size: 12px; line-height: normal; white-space: nowrap; widows: 1; background-color: rgb(218, 240, 249);">
Stack Trace
Class.Trigger_Task_Send_Email_Test1.emailTest_single: line 15, column 1
pconpcon
Do you happen to have the full stack trace?  That occurs when there is a problem in your trigger.  The full stack trace can help us pinpoint where it is failing in the trigger.  Then we can either fix the trigger code, or update the test method to have the information set that the trigger expects.
Christian ØelundChristian Øelund
How do I get Full stack trace. Is that something I can find in the developer console?
pconpcon
You should be able to run the test (either via the dev console or via setup -> develop -> apex test execution).  Then in the test results you should be able to see the full stack trace.  Otherwise you can download the log from the test execution and see the stack trace in there.
Christian ØelundChristian Øelund
This is my log from the test class:

29.0 APEX_CODE,FINEST;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO;WORKFLOW,INFO
00:36:33.051 (51186962)|EXECUTION_STARTED
00:36:33.051 (51251424)|CODE_UNIT_STARTED|[EXTERNAL]|01p260000004I6H|Trigger_Task_Send_Email_Test1.emailTest_single
00:36:33.051 (51884839)|HEAP_ALLOCATE|[71]|Bytes:3
00:36:33.051 (51924312)|HEAP_ALLOCATE|[76]|Bytes:152
00:36:33.051 (51947999)|HEAP_ALLOCATE|[272]|Bytes:408
00:36:33.051 (51974150)|HEAP_ALLOCATE|[285]|Bytes:408
00:36:33.051 (51998009)|HEAP_ALLOCATE|[379]|Bytes:48
00:36:33.052 (52032198)|HEAP_ALLOCATE|[131]|Bytes:6
00:36:33.052 (52058934)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:27
00:36:33.052 (52076054)|METHOD_ENTRY|[2]|01p260000004I6H|Trigger_Task_Send_Email_Test1.Trigger_Task_Send_Email_Test1()
00:36:33.052 (52081982)|STATEMENT_EXECUTE|[2]
00:36:33.052 (52087128)|STATEMENT_EXECUTE|[2]
00:36:33.052 (52092798)|METHOD_EXIT|[2]|Trigger_Task_Send_Email_Test1
00:36:33.052 (52131724)|HEAP_ALLOCATE|[50]|Bytes:5
00:36:33.052 (52154328)|HEAP_ALLOCATE|[56]|Bytes:5
00:36:33.052 (52164960)|HEAP_ALLOCATE|[63]|Bytes:7
00:36:33.052 (52207735)|STATEMENT_EXECUTE|[3]
00:36:33.052 (52212043)|STATEMENT_EXECUTE|[4]
00:36:33.052 (52276895)|HEAP_ALLOCATE|[4]|Bytes:4
00:36:33.052 (52394756)|HEAP_ALLOCATE|[4]|Bytes:11
00:36:33.053 (53732696)|VARIABLE_ASSIGNMENT|[4]|this.Subject|"Test Task 1"|0x636153af
00:36:33.053 (53771285)|SYSTEM_METHOD_ENTRY|[4]|com.salesforce.api.interop.apex.bcl.DateMethods.today()
00:36:33.053 (53822915)|HEAP_ALLOCATE|[4]|Bytes:4
00:36:33.053 (53833165)|SYSTEM_METHOD_EXIT|[4]|com.salesforce.api.interop.apex.bcl.DateMethods.today()
00:36:33.053 (53891285)|VARIABLE_ASSIGNMENT|[4]|this.ActivityDate|"2015-05-22T00:00:00.000Z"|0x636153af
00:36:33.053 (53921600)|VARIABLE_SCOPE_BEGIN|[4]|testTask|Task|true|false
00:36:33.053 (53950776)|VARIABLE_ASSIGNMENT|[4]|testTask|{"Subject":"Test Task 1","ActivityDate":"2015-05-22T00:00:00.000Z"}|0x636153af
00:36:33.053 (53956788)|STATEMENT_EXECUTE|[8]
00:36:33.053 (53990074)|HEAP_ALLOCATE|[8]|Bytes:8
00:36:33.054 (54010681)|DML_BEGIN|[8]|Op:Insert|Type:Task|Rows:1
00:36:33.054 (54034373)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
00:36:33.091 (91153319)|CODE_UNIT_STARTED|[EXTERNAL]|Workflow:Task
00:36:33.099 (99845002)|WF_RULE_EVAL_BEGIN|Workflow
00:36:33.099 (99876079)|WF_CRITERIA_BEGIN|[Task:  00T26000001bNb3]|Uncheck|01Q240000000HJ4|ON_ALL_CHANGES|0
00:36:33.100 (100163817)|WF_FORMULA|Formula:ENCODED:[treatNullAsNull]ISCHANGED({!ID:Owner})|Values:OwnerId=00524000000LRGK
00:36:33.100 (100172095)|WF_CRITERIA_END|false
00:36:33.100 (100190104)|WF_SPOOL_ACTION_BEGIN|Workflow
00:36:33.100 (100197419)|WF_ACTION| None
00:36:33.100 (100201332)|WF_RULE_EVAL_END
00:36:33.100 (100235140)|WF_ACTIONS_END| None
00:36:33.100 (100241482)|CODE_UNIT_FINISHED|Workflow:Task
00:36:33.100 (100927479)|DML_END|[8]
00:36:33.100 (100946081)|STATEMENT_EXECUTE|[10]
00:36:33.100 (100967916)|SYSTEM_METHOD_ENTRY|[10]|Limit.getEmailInvocations()
00:36:33.101 (101000379)|SYSTEM_METHOD_EXIT|[10]|Limit.getEmailInvocations()
00:36:33.101 (101007633)|VARIABLE_SCOPE_BEGIN|[10]|emailsSentPre|Integer|false|false
00:36:33.101 (101012989)|HEAP_ALLOCATE|[10]|Bytes:4
00:36:33.101 (101024221)|VARIABLE_ASSIGNMENT|[10]|emailsSentPre|0
00:36:33.101 (101028512)|STATEMENT_EXECUTE|[12]
00:36:33.101 (101097001)|SYSTEM_METHOD_ENTRY|[12]|system.Test.startTest()
00:36:33.102 (102831957)|SYSTEM_METHOD_EXIT|[12]|system.Test.startTest()
00:36:33.102 (102840115)|STATEMENT_EXECUTE|[14]
00:36:33.102 (102845964)|HEAP_ALLOCATE|[14]|Bytes:11
00:36:33.102 (102892227)|VARIABLE_ASSIGNMENT|[14]|this.Subject|"Test Task 2"|0x636153af
00:36:33.102 (102898971)|STATEMENT_EXECUTE|[15]
00:36:33.102 (102921874)|HEAP_ALLOCATE|[15]|Bytes:8
00:36:33.102 (102935042)|DML_BEGIN|[15]|Op:Update|Type:Task|Rows:1
00:36:33.102 (102958048)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
00:36:33.127 (127480104)|CODE_UNIT_STARTED|[EXTERNAL]|01q260000004D4P|Trigger_Task_Send_Email on Task trigger event BeforeUpdate for [00T26000001bNb3]
00:36:33.127 (127538002)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
00:36:33.127 (127566072)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
00:36:33.127 (127766957)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:12
00:36:33.127 (127784350)|VARIABLE_SCOPE_BEGIN|[1]|this|Trigger_Task_Send_Email|true|false
00:36:33.127 (127846449)|VARIABLE_ASSIGNMENT|[1]|this|{}|0x131b12dc
00:36:33.127 (127897105)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:12
00:36:33.127 (127909006)|VARIABLE_SCOPE_BEGIN|[1]|this|Trigger_Task_Send_Email|true|false
00:36:33.127 (127931464)|VARIABLE_ASSIGNMENT|[1]|this|{}|0x131b12dc
00:36:33.127 (127939118)|STATEMENT_EXECUTE|[1]
00:36:33.127 (127942273)|STATEMENT_EXECUTE|[5]
00:36:33.127 (127953358)|HEAP_ALLOCATE|[5]|Bytes:4
00:36:33.127 (127977972)|SYSTEM_CONSTRUCTOR_ENTRY|[5]|<init>(Integer)
00:36:33.128 (128002684)|SYSTEM_CONSTRUCTOR_EXIT|[5]|<init>(Integer)
00:36:33.128 (128082213)|VARIABLE_ASSIGNMENT|[5]|this.createdbyIds|{"serId":1,"value":[]}|0x131b12dc
00:36:33.128 (128183398)|SYSTEM_METHOD_ENTRY|[7]|List<Task>.iterator()
00:36:33.128 (128318712)|SYSTEM_METHOD_EXIT|[7]|List<Task>.iterator()
00:36:33.128 (128346302)|SYSTEM_METHOD_ENTRY|[7]|system.ListIterator.hasNext()
00:36:33.128 (128373598)|HEAP_ALLOCATE|[7]|Bytes:5
00:36:33.128 (128383401)|SYSTEM_METHOD_EXIT|[7]|system.ListIterator.hasNext()
00:36:33.128 (128400222)|HEAP_ALLOCATE|[7]|Bytes:4
00:36:33.128 (128410327)|VARIABLE_SCOPE_BEGIN|[7]|tsk|Task|true|false
00:36:33.128 (128737870)|VARIABLE_ASSIGNMENT|[7]|tsk|{"LastModifiedById":"00524000000LRGKAA4","Subject":"Test Task 2","OwnerId":"00524000000LRGKAA4","LastModifiedDate":"2015-05-21T22:36:33.000Z","ActivityDate":"2015-05-22T00:00:00.000Z","IsRecurrence":false,"Priority":"Normal","IsArchived":false,"Status":"Not Started","IsClosed":false,"Task_Accepted__c":true,"IsReminderSet":false,"SystemModstamp":"2015-05-21T22:36:33.000Z","CreatedById":"00524000000LRGKAA4","CreatedDate":"2015-05-21T22:36:33.000Z","IsDeleted":false,"Type__c":"Other","Id":"00T26000001bNb3EAE"}|0x1da2b2bd
00:36:33.128 (128750258)|STATEMENT_EXECUTE|[8]
00:36:33.128 (128794622)|SYSTEM_METHOD_ENTRY|[8]|Set<Id>.add(Object)
00:36:33.128 (128817294)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:4
00:36:33.128 (128830277)|SYSTEM_METHOD_EXIT|[8]|Set<Id>.add(Object)
00:36:33.128 (128839156)|SYSTEM_METHOD_ENTRY|[7]|system.ListIterator.hasNext()
00:36:33.128 (128848661)|HEAP_ALLOCATE|[7]|Bytes:5
00:36:33.128 (128855746)|SYSTEM_METHOD_EXIT|[7]|system.ListIterator.hasNext()
00:36:33.128 (128868647)|VARIABLE_ASSIGNMENT|[7]|tsk|null|
00:36:33.128 (128874228)|STATEMENT_EXECUTE|[11]
00:36:33.128 (128882784)|HEAP_ALLOCATE|[11]|Bytes:4
00:36:33.128 (128888617)|HEAP_ALLOCATE|[11]|Bytes:48
00:36:33.128 (128896917)|HEAP_ALLOCATE|[11]|Bytes:4
00:36:33.128 (128906721)|HEAP_ALLOCATE|[11]|Bytes:7
00:36:33.129 (129094281)|SOQL_EXECUTE_BEGIN|[11]|Aggregations:0|SELECT Name, Email FROM User WHERE Id = :tmpVar1
00:36:33.132 (132489385)|SOQL_EXECUTE_END|[11]|Rows:1
00:36:33.132 (132502581)|HEAP_ALLOCATE|[11]|Bytes:8
00:36:33.132 (132516629)|HEAP_ALLOCATE|[11]|Bytes:89
00:36:33.132 (132559685)|HEAP_ALLOCATE|[11]|Bytes:8
00:36:33.132 (132617999)|HEAP_ALLOCATE|[11]|Bytes:16
00:36:33.132 (132629347)|HEAP_ALLOCATE|[11]|Bytes:4
00:36:33.132 (132682095)|VARIABLE_ASSIGNMENT|[11]|this.userMap|{"serId":1,"value":{"00524000000LRGKAA4":{"serId":2,"value":{"Name":"Christian Øelund","Email":"christianoelund@hotm (7 more) ...","Id":"00524000000LRGKAA4"}}}}|0x131b12dc
00:36:33.132 (132709759)|SYSTEM_METHOD_ENTRY|[12]|List<Task>.iterator()
00:36:33.132 (132729961)|SYSTEM_METHOD_EXIT|[12]|List<Task>.iterator()
00:36:33.132 (132739119)|SYSTEM_METHOD_ENTRY|[12]|system.ListIterator.hasNext()
00:36:33.132 (132749274)|HEAP_ALLOCATE|[12]|Bytes:5
00:36:33.132 (132756659)|SYSTEM_METHOD_EXIT|[12]|system.ListIterator.hasNext()
00:36:33.132 (132767218)|HEAP_ALLOCATE|[12]|Bytes:4
00:36:33.132 (132775448)|VARIABLE_SCOPE_BEGIN|[12]|tsk|Task|true|false
00:36:33.132 (132948179)|VARIABLE_ASSIGNMENT|[12]|tsk|{"LastModifiedById":"00524000000LRGKAA4","Subject":"Test Task 2","OwnerId":"00524000000LRGKAA4","LastModifiedDate":"2015-05-21T22:36:33.000Z","ActivityDate":"2015-05-22T00:00:00.000Z","IsRecurrence":false,"Priority":"Normal","IsArchived":false,"Status":"Not Started","IsClosed":false,"Task_Accepted__c":true,"IsReminderSet":false,"SystemModstamp":"2015-05-21T22:36:33.000Z","CreatedById":"00524000000LRGKAA4","CreatedDate":"2015-05-21T22:36:33.000Z","IsDeleted":false,"Type__c":"Other","Id":"00T26000001bNb3EAE"}|0x1da2b2bd
00:36:33.132 (132960274)|STATEMENT_EXECUTE|[13]
00:36:33.132 (132963270)|STATEMENT_EXECUTE|[14]
00:36:33.132 (132999536)|SYSTEM_METHOD_ENTRY|[14]|Map<Id,User>.get(Object)
00:36:33.133 (133027879)|SYSTEM_METHOD_EXIT|[14]|Map<Id,User>.get(Object)
00:36:33.133 (133035534)|VARIABLE_SCOPE_BEGIN|[14]|theUser|User|true|false
00:36:33.133 (133056089)|VARIABLE_ASSIGNMENT|[14]|theUser|{"serId":1,"value":{"Name":"Christian Øelund","Email":"christianoelund@hotm (7 more) ...","Id":"00524000000LRGKAA4"}}|0x622768f5
00:36:33.133 (133062385)|STATEMENT_EXECUTE|[15]
00:36:33.133 (133121248)|VARIABLE_SCOPE_BEGIN|[15]|mail|Messaging.SingleEmailMessage|true|false
00:36:33.133 (133204141)|VARIABLE_ASSIGNMENT|[15]|mail|"common.api.soap.wsdl.SingleEmailMessage@95bdf2b"|0x6e9884d9
00:36:33.133 (133212650)|STATEMENT_EXECUTE|[16]
00:36:33.133 (133224019)|HEAP_ALLOCATE|[16]|Bytes:4
00:36:33.133 (133236028)|SYSTEM_CONSTRUCTOR_ENTRY|[16]|<init>()
00:36:33.133 (133251519)|SYSTEM_CONSTRUCTOR_EXIT|[16]|<init>()
00:36:33.133 (133281697)|VARIABLE_SCOPE_BEGIN|[16]|toAddresses|List<String>|true|false
00:36:33.133 (133307896)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
00:36:33.133 (133328082)|VARIABLE_ASSIGNMENT|[16]|toAddresses|{"serId":1,"value":["christianoelund@hotm (7 more) ..."]}|0x5f39fb48
00:36:33.133 (133333965)|STATEMENT_EXECUTE|[17]
00:36:33.133 (133378701)|STATEMENT_EXECUTE|[18]
00:36:33.133 (133385501)|HEAP_ALLOCATE|[18]|Bytes:38
00:36:33.133 (133422072)|STATEMENT_EXECUTE|[21]
00:36:33.133 (133427945)|HEAP_ALLOCATE|[21]|Bytes:65
00:36:33.133 (133433300)|VARIABLE_SCOPE_BEGIN|[21]|template|String|false|false
00:36:33.133 (133445513)|VARIABLE_ASSIGNMENT|[21]|template|"Hello {0}, \nYour tas (45 more) ..."
00:36:33.133 (133449535)|STATEMENT_EXECUTE|[22]
00:36:33.133 (133453054)|HEAP_ALLOCATE|[22]|Bytes:14
00:36:33.133 (133473116)|HEAP_ALLOCATE|[22]|Bytes:79
00:36:33.133 (133483215)|VARIABLE_ASSIGNMENT|[22]|template|"Hello {0}, \nYour tas (59 more) ..."
00:36:33.133 (133487213)|STATEMENT_EXECUTE|[23]
00:36:33.133 (133490990)|HEAP_ALLOCATE|[23]|Bytes:15
00:36:33.133 (133496230)|HEAP_ALLOCATE|[23]|Bytes:94
00:36:33.133 (133504583)|VARIABLE_ASSIGNMENT|[23]|template|"Hello {0}, \nYour tas (74 more) ..."
00:36:33.133 (133508303)|STATEMENT_EXECUTE|[24]
00:36:33.133 (133515331)|VARIABLE_SCOPE_BEGIN|[24]|duedate|String|false|false
00:36:33.133 (133521979)|VARIABLE_ASSIGNMENT|[24]|duedate|""
00:36:33.133 (133558037)|STATEMENT_EXECUTE|[28]
00:36:33.133 (133577142)|SYSTEM_METHOD_ENTRY|[28]|com.salesforce.api.interop.apex.bcl.DateMethods.format()
00:36:33.133 (133675755)|HEAP_ALLOCATE|[28]|Bytes:10
00:36:33.133 (133686931)|SYSTEM_METHOD_EXIT|[28]|com.salesforce.api.interop.apex.bcl.DateMethods.format()
00:36:33.133 (133699020)|VARIABLE_ASSIGNMENT|[28]|duedate|"22-05-2015"
00:36:33.133 (133703257)|STATEMENT_EXECUTE|[29]
00:36:33.133 (133709101)|HEAP_ALLOCATE|[29]|Bytes:4
00:36:33.133 (133715715)|SYSTEM_CONSTRUCTOR_ENTRY|[29]|<init>()
00:36:33.133 (133730442)|SYSTEM_CONSTRUCTOR_EXIT|[29]|<init>()
00:36:33.133 (133734939)|VARIABLE_SCOPE_BEGIN|[29]|args|List<String>|true|false
00:36:33.133 (133749019)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:4
00:36:33.133 (133764350)|VARIABLE_ASSIGNMENT|[29]|args|{"serId":1,"value":[]}|0x3995dcc6
00:36:33.133 (133769979)|STATEMENT_EXECUTE|[30]
00:36:33.133 (133804155)|SYSTEM_METHOD_ENTRY|[30]|List<String>.add(Object)
00:36:33.133 (133826461)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:4
00:36:33.133 (133837668)|SYSTEM_METHOD_EXIT|[30]|List<String>.add(Object)
00:36:33.133 (133842472)|STATEMENT_EXECUTE|[31]
00:36:33.133 (133869405)|SYSTEM_METHOD_ENTRY|[31]|List<String>.add(Object)
00:36:33.133 (133887014)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:4
00:36:33.133 (133897255)|SYSTEM_METHOD_EXIT|[31]|List<String>.add(Object)
00:36:33.133 (133901921)|STATEMENT_EXECUTE|[32]
00:36:33.133 (133911662)|SYSTEM_METHOD_ENTRY|[32]|List<String>.add(Object)
00:36:33.133 (133926832)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:4
00:36:33.133 (133936415)|SYSTEM_METHOD_EXIT|[32]|List<String>.add(Object)
00:36:33.133 (133940825)|STATEMENT_EXECUTE|[36]
00:36:33.133 (133965003)|SYSTEM_METHOD_ENTRY|[36]|String.format(String, List<String>)
00:36:33.134 (134004271)|HEAP_ALLOCATE|[36]|Bytes:16
00:36:33.134 (134014980)|HEAP_ALLOCATE|[36]|Bytes:11
00:36:33.134 (134018187)|HEAP_ALLOCATE|[36]|Bytes:10
00:36:33.134 (134027340)|HEAP_ALLOCATE|[36]|Bytes:122
00:36:33.134 (134040618)|SYSTEM_METHOD_EXIT|[36]|String.format(String, List<String>)
00:36:33.134 (134046201)|VARIABLE_SCOPE_BEGIN|[36]|formattedHtml|String|false|false
00:36:33.134 (134057599)|VARIABLE_ASSIGNMENT|[36]|formattedHtml|"Hello Christian Øelu (102 more) ..."
00:36:33.134 (134061874)|STATEMENT_EXECUTE|[38]
00:36:33.134 (134093283)|STATEMENT_EXECUTE|[39]
00:36:33.134 (134118311)|HEAP_ALLOCATE|[39]|Bytes:4
00:36:33.134 (134158797)|SYSTEM_CONSTRUCTOR_ENTRY|[39]|<init>()
00:36:33.134 (134177904)|SYSTEM_CONSTRUCTOR_EXIT|[39]|<init>()
00:36:33.134 (134211947)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
00:36:33.134 (134226966)|SYSTEM_METHOD_ENTRY|[39]|Messaging.sendEmail(List<Messaging.Email>)
00:36:33.134 (134247868)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
00:36:33.136 (136779428)|EXCEPTION_THROWN|[39]|System.EmailException: SendEmail failed. First exception on row 0; first error: NO_MASS_MAIL_PERMISSION, Single email is not enabled for your organization or profile.  Single email must be enabled for you to use this feature.: []
00:36:33.137 (137383483)|HEAP_ALLOCATE|[39]|Bytes:210
00:36:33.137 (137396705)|SYSTEM_METHOD_EXIT|[39]|Messaging.sendEmail(List<Messaging.Email>)
00:36:33.137 (137454128)|FATAL_ERROR|System.EmailException: SendEmail failed. First exception on row 0; first error: NO_MASS_MAIL_PERMISSION, Single email is not enabled for your organization or profile.  Single email must be enabled for you to use this feature.: []

Trigger.Trigger_Task_Send_Email: line 39, column 1
00:36:33.137 (137469088)|FATAL_ERROR|System.EmailException: SendEmail failed. First exception on row 0; first error: NO_MASS_MAIL_PERMISSION, Single email is not enabled for your organization or profile.  Single email must be enabled for you to use this feature.: []

Trigger.Trigger_Task_Send_Email: line 39, column 1
00:36:33.900 (137487792)|CUMULATIVE_LIMIT_USAGE
00:36:33.900|LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 0 out of 100
  Number of query rows: 0 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 2 out of 150
  Number of DML rows: 2 out of 10000
  Maximum CPU time: 0 out of 10000
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 100
  Number of Email Invocations: 0 out of 10
  Number of future calls: 0 out of 50
  Number of queueable jobs added to the queue: 0 out of 50
  Number of Mobile Apex push calls: 0 out of 10

00:36:33.900|TESTING_LIMITS
00:36:33.900|LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 1 out of 100
  Number of query rows: 1 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 0 out of 150
  Number of DML rows: 0 out of 10000
  Maximum CPU time: 0 out of 10000
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 100
  Number of Email Invocations: 0 out of 10
  Number of future calls: 0 out of 50
  Number of queueable jobs added to the queue: 0 out of 50
  Number of Mobile Apex push calls: 0 out of 10

00:36:33.900|CUMULATIVE_LIMIT_USAGE_END

00:36:33.137 (137698486)|CODE_UNIT_FINISHED|Trigger_Task_Send_Email on Task trigger event BeforeUpdate for [00T26000001bNb3]
00:36:33.138 (138794002)|DML_END|[15]
00:36:33.138 (138871629)|EXCEPTION_THROWN|[15]|System.DmlException: Update failed. First exception on row 0 with id 00T26000001bNb3EAE; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Trigger_Task_Send_Email: execution of BeforeUpdate

caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: NO_MASS_MAIL_PERMISSION, Single email is not enabled for your organization or profile.  Single email must be enabled for you to use this feature.: []

Trigger.Trigger_Task_Send_Email: line 39, column 1: []
00:36:33.139 (139195358)|HEAP_ALLOCATE|[15]|Bytes:471
00:36:33.139 (139237275)|FATAL_ERROR|System.DmlException: Update failed. First exception on row 0 with id 00T26000001bNb3EAE; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Trigger_Task_Send_Email: execution of BeforeUpdate

caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: NO_MASS_MAIL_PERMISSION, Single email is not enabled for your organization or profile.  Single email must be enabled for you to use this feature.: []

Trigger.Trigger_Task_Send_Email: line 39, column 1: []

Class.Trigger_Task_Send_Email_Test1.emailTest_single: line 15, column 1
00:36:33.139 (139251814)|FATAL_ERROR|System.DmlException: Update failed. First exception on row 0 with id 00T26000001bNb3EAE; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Trigger_Task_Send_Email: execution of BeforeUpdate

caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: NO_MASS_MAIL_PERMISSION, Single email is not enabled for your organization or profile.  Single email must be enabled for you to use this feature.: []

Trigger.Trigger_Task_Send_Email: line 39, column 1: []

Class.Trigger_Task_Send_Email_Test1.emailTest_single: line 15, column 1
00:36:33.902 (139267163)|CUMULATIVE_LIMIT_USAGE
00:36:33.902|LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 0 out of 100
  Number of query rows: 0 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 2 out of 150
  Number of DML rows: 2 out of 10000
  Maximum CPU time: 0 out of 10000
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 100
  Number of Email Invocations: 0 out of 10
  Number of future calls: 0 out of 50
  Number of queueable jobs added to the queue: 0 out of 50
  Number of Mobile Apex push calls: 0 out of 10

00:36:33.902|TESTING_LIMITS
00:36:33.902|LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 0 out of 100
  Number of query rows: 0 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 0 out of 150
  Number of DML rows: 0 out of 10000
  Maximum CPU time: 0 out of 10000
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 100
  Number of Email Invocations: 0 out of 10
  Number of future calls: 0 out of 50
  Number of queueable jobs added to the queue: 0 out of 50
  Number of Mobile Apex push calls: 0 out of 10

00:36:33.902|CUMULATIVE_LIMIT_USAGE_END

00:36:33.139 (139298915)|CODE_UNIT_FINISHED|Trigger_Task_Send_Email_Test1.emailTest_single
00:36:33.140 (140357458)|EXECUTION_FINISHED
Christian ØelundChristian Øelund
I Updated the email security and now im only getting this error 
System.AssertException: Assertion Failed: We should have only sent one email: Expected: 1, Actual: 0
Stack Trace Class.Trigger_Task_Send_Email_Test1.emailTest_single: line 22, column 1
pconpcon
Is then when deploying or when running the tests in the development sandbox?
Christian ØelundChristian Øelund
The results above is from running the test in SB mode. Here is the results when i try to deploy in production.
User-added image
pconpcon
If you run the test in the developer console does it pass?  If it does not, comment out the System.assert line, re-run and check to see if line 35 of Trigger_Task_Send_Email is executed in your test.
Christian ØelundChristian Øelund
Thank you so much for your time. it's deployed and works fine.
Dnyaneshwar Mandwade 9Dnyaneshwar Mandwade 9
 I got below error while test it on developer console in test class.
Error:  Class.SalesForceContact.doGet: line 38, column 1 Class.SalesForceContatTest.testGetCount: line 9, column 1
 
Below is this my actual apex class:  

@RestResource(urlMapping='/api/salesforcecontact/*')
global class SalesForceContact
{
   @HttpGet
global static Integer getCount()
{
Integer recordCount = [SELECT COUNT() FROM Contact];
return recordCount ;
}

 @HttpPost
global static LIST<Contact> doGet(Integer PageNumber, Integer PageSize, String LastCreatedDate) 
    {
LIST<Contact> jsonData;

String objName= 'Contact'; 
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Map<String, Schema.SObjectField> fieldMap = schemaMap.get(objName).getDescribe().fields.getMap();
String fields= '';
for(String fieldName : fieldMap.keyset()){
if(fields == null || fields== ''){
fields= fieldName;
}else{
fields= fields+ ', ' + fieldName;
}


String query='';
 if (PageNumber == 0)
 {
     query = 'select ' + fields+ ' from ' + objName +' ORDER BY CreatedDate LIMIT '+ PageSize;
 }
 else 
 {
     query ='select ' + fields+ ' from ' + objName +' WHERE CreatedDate >'+ LastCreatedDate +' ORDER BY CreatedDate LIMIT '+PageSize;
 }
 
 jsonData = Database.query(query);
 return jsonData ;
}   
}

Please help 
 
pconpcon
I've taken the liberty to clean up your code a little bit and make it more readable and re-usable.  Can you please run this code and let me know which line number are failing (based on the line numbers in the code block below) as well as what the actual error messages are.  You only included the line numbers that are failing and not what the failure message is from the tests.
 
@RestResource(urlMapping='/api/salesforcecontact/*')
global class SalesForceContact {
    @HttpGet
    global static Integer getCount() {
        Integer recordCount = [
            select COUNT()
            from Contact
        ];
        return recordCount;
    }

    @HttpPost
    global static List<Contact> doGet(Integer pageNumber, Integer pageSize, String lastCreatedDate) {
        String objName = Schema.sObjectType.Contact.getName()
        Map<String, Schema.sObjectField> fieldMap = Schema.getGlobalDescribe().get(objName).getDescribe().fields.getMap();

        List<String> fields = new List<String>();
        fields.addAll(fieldMap.keySet());

        List<String> queryParts = new List<String> {
            'select ' + fields.join(','),
            'from ' + objName
        };

        if (pageNumber > 0) {
            queryParts.add('where CreatedDate > ' + String.escapeSingleQuotes(lastCreatedDate));
        }

        queryParts.add('order by CreatedDate');
        queryParts.add('limit ' + pageSize);

        return (List<Contact>)(Database.query(String.join(query, ' '));
    }
}
NOTE: The code above has not been tested and may contain typographical and / or logical errors.
NOTE: Please use the "Add a Code Sample" button (icon <>) when adding code to make it easier to read and reference.