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
krishna casukhela 7krishna casukhela 7 

Test.StartTest & Test.StopTest

Hi friends

I have written code that updates email of contact object when BillingState='Karnataka' of acocunt object.
Apex class & trigger working fine.

Now I write test class as below
public class sampleTestMethodCls
{
  private static testMethod void testAccountTrigger()
  {
        //First, prepare 200 contacts for the test data
         Account acct = new Account(name='test account');

         insert acct;

         Contact[] contactsToCreate = new Contact[]{};

         for(Integer x=0; x<200;x++)
        {
         Contact ct = new Contact(AccountId=acct.Id,lastname='test');
         contactsToCreate.add(ct);
        }

        //Now insert data causing an contact trigger to fire.

        Test.startTest();

        insert contactsToCreate;

         Test.stopTest();   
     }  
 }

when I Run the test class I get an error as " Test methods must be in test classes at line 4 column 36"

Please let me know what is exact reason of this error:? & how it impact performance:?

Thanks
Krishna casukhela
 
Vivek DeshmaneVivek Deshmane
Please below code and let me know if it works.
@isTest
public class sampleTestMethodCls
{
  private static testMethod void testAccountTrigger()
  {
        //First, prepare 200 contacts for the test data
         Account acct = new Account(name='test account');

         insert acct;

         Contact[] contactsToCreate = new Contact[]{};

         for(Integer x=0; x<200;x++)
        {
         Contact ct = new Contact(AccountId=acct.Id,lastname='test');
         contactsToCreate.add(ct);
        }

        //Now insert data causing an contact trigger to fire.

        Test.startTest();

        insert contactsToCreate;

         Test.stopTest();   
     }  
 }
Best Regards,
-Vivek
Vivek DeshmaneVivek Deshmane
Hi ,

Refer following link for more detail.
https://developer.salesforce.com/page/An_Introduction_to_Apex_Code_Test_Methods

Best Regards,
-Vivek
Amit Chaudhary 8Amit Chaudhary 8
NOTE:- You was forget to add @isTest in test class.

Defining classes of test methods with the isTest annotation
Use the isTest class annotation to define classes that only contain code used for testing your application. If your test methods are contained within their own classes and the Apex class only contains test methods, it is ideal to use the isTest annotation.

Test.startTest/Test.stopTest
There are two additional system static methods provided by Apex. These methods, Test.startTest and Test.stopTest, are used when testing governor limits. Or in other words, executing test scenarios with a larger data set.

The Test.startTest method marks the point in your test code when your test actually begins. Each test method is allowed to call this method only once. All of the code before this method should be used to initialize variables, populate data structures, and so on, allowing you to set up everything you need in order to run your test. After you call this method, you get a fresh set of governor limits for the remainder of the test until you call Test.stopTest.

The Test.stopTest method marks the point in your test code when your test ends. Use this method in conjunction with thestartTest method. Each test method is allowed to call this method only once. After calling this method, any post assertions are done in the original context

Please try below code:-

@isTest

public class sampleTestMethodCls
{
  private static testMethod void testAccountTrigger()
  {
        //First, prepare 200 contacts for the test data
         Account acct = new Account(name='test account');

         insert acct;

         Contact[] contactsToCreate = new Contact[]{};

         for(Integer x=0; x<200;x++)
        {
         Contact ct = new Contact(AccountId=acct.Id,lastname='test');
         contactsToCreate.add(ct);
        }

        //Now insert data causing an contact trigger to fire.

        Test.startTest();

        insert contactsToCreate;

         Test.stopTest();   
     }  
 }

Please check more detail on test classes one below blog
http://amitsalesforce.blogspot.in/2015/06/best-practice-for-test-classes-sample.html

Please follow below salesforce Best Practice for Test Classes :-

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required 
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can't be a interface or enum .
15. Test method code can't be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock .
19. You can't  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .


Please let us know if this post will help you

Thanks,
Amit Chaudhary
RajnisfRajnisf
Methods defined as TestMethod do not support Web service callouts...not able to understand


Global class unsubscribe implements Messaging.inboundEmailHandler{

Global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, 
                            Messaging.InboundEnvelope env ) {

// Create an inboundEmailResult object for returning 
//the result of the Apex Email Service
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
 
// Contact and Lead lists to hold all the updated records
List<Contact> lc = new List <contact>();
List<Lead> ll = new List <lead>();
 
// Convert the subject line to lower case, so I can match on lower case
String mySubject = email.subject.toLowerCase();
// String I am searching for in the subject line
String s = 'unsubscribe';
 
// Check variable to see if the word "unsubscribe" was found in the subject line 
Boolean unsubMe;
// Look for the unsubcribe word in the subject line, 
// if it is found return true, otherwise false is returned
unsubMe = mySubject.contains(s);
 
 // If unsubscribe is found in the subject line enter the if statement
 
 if (unsubMe == true) {
    
    try {
        
    // Lookup all contacts with a matching email address
        
     for (Contact c : [Select Id, Name, Email, HasOptedOutOfEmail
                        From Contact
                        Where Email = :env.fromAddress
                        And hasOptedOutOfEmail = false
                        Limit 100]) {
                        
        // Add all the contacts into the List   
                            c.hasOptedOutOfEmail = true;
                            lc.add(c);                                 
    }    
        // update all the Contact records
        
        update lc;
            }
    catch (System.QueryException e) {
        System.debug('Contact Query Issue: ' + e);
        }   

    try {
        // Lookup all leads matching the email address
     for (Lead l : [Select Id, Name, Email, HasOptedOutOfEmail
                        From Lead
                        Where Email = :env.fromAddress
                        And isConverted = false
                        And hasOptedOutOfEmail = false
                        Limit 100]) {
        // Add all the leads to the List        
        l.hasOptedOutOfEmail = true;
        ll.add(l);
                               
           System.debug('Lead Object: ' + l);   
    }    
        // Update all Lead records in the query
        update ll;
            }

    catch (System.QueryException e) {
        System.debug('Lead Query Issue: ' + e);
        }   

    System.debug('Found the unsubscribe word in the subject line.');
 } 
 else {
    System.debug('No Unsuscribe word found in the subject line.' );
 }
// Return true and exit
// True will confirm it is complete and no bounced email 
// should be send the sender of the unsubscribe request. 
result.success = true;
return result;
    }   
    
    // Test method to ensure you have enough code coverage
    // Have created two methods, one that does the testing
    // with a valid "unsubcribe" in the subject line
    // and one the does not contain "unsubscribe" in the
    // subject line
    
static testMethod void testUnsubscribe() {

// Create a new email and envelope object
   Messaging.InboundEmail email = new Messaging.InboundEmail() ;
   Messaging.InboundEnvelope env    = new Messaging.InboundEnvelope();

// Create a new test Lead and insert it in the Test Method        
   Lead l = new lead(firstName='Rasmus', 
            lastName='Mencke',
            Company='Salesforce', 
            Email='rmencke@salesforce.com', 
            HasOptedOutOfEmail=false);
   insert l;

// Create a new test Contact and insert it in the Test Method  
   Contact c = new Contact(firstName='Rasmus', 
                lastName='Mencke', 
                Email='rmencke@salesforce.com', 
                HasOptedOutOfEmail=false);
   insert c;
   
   // test with subject that matches the unsubscribe statement
   email.subject = 'test unsubscribe test';
   env.fromAddress = 'rmencke@salesforce.com';
   
   // call the class and test it with the data in the testMethod
   unsubscribe unsubscribeObj = new unsubscribe();
   unsubscribeObj.handleInboundEmail(email, env );
                        
   }
 
static testMethod void testUnsubscribe2() {

// Create a new email and envelope object
   Messaging.InboundEmail email = new Messaging.InboundEmail();
   Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();

// Create a new test Lead and insert it in the Test Method        
   Lead l = new lead(firstName='Rasmus', 
            lastName='Mencke',
            Company='Salesforce', 
            Email='rmencke@salesforce.com', 
            HasOptedOutOfEmail=false);
   insert l;

// Create a new test Contact and insert it in the Test Method    
   Contact c = new Contact(firstName='Rasmus', 
                lastName='Mencke', 
                Email='rmencke@salesforce.com', 
                HasOptedOutOfEmail=false);
   insert c;
   
   // Test with a subject that does Not contain unsubscribe
   email.subject = 'test';
   env.fromAddress = 'rmencke@salesforce.com';

   // call the class and test it with the data in the testMethod
   unsubscribe unsubscribeObj = new unsubscribe();
   unsubscribeObj.handleInboundEmail(email, env );                      
   }    
   
}
Saqib Qamar 5Saqib Qamar 5
Well Defined !!!