Salesforce Platform dev 1 Apex Testing 1

Writing test class is very essential before you deploy your code to production

from sandbox.

If your code coverage is not above 75 percent you won't be able to deploy

your code.


Let's create a simple scenario where you would like to create an Apex class

which contains a method to create account and contact and link the account to this

newly created contact.


Create a new class


public class AccountClass {

    

    public static void CreateAccountandContact()

    {

        try

        {

           account a = new account();

           a.name = 'Demo acc Test';

           insert a;

            

           contact c = new contact();

           c.LastName = 'Demo last name';

           c.AccountId= a.id;

           insert c; 

             

            

            

        }

        catch(exception ex)

        {

            system.debug(ex.getMessage());

            

        }

        

    }

    

  

 

}

Write a test class 


@istest

public class DemoAccContTest 

{

  @istest private static void TestAccandContact()

   {

       system.test.startTest();

       AccountClass.CreateAccountandContact();

       integer contactcount = [select count() from contact];

       system.assert(contactcount==26);

       system.test.stopTest();

       

   }

}


By default (seealldata=false) which means you cant rely on production

underlying data for your test.

if you want to use production data as part of your test case then you

need to include (seealldata=true) as shown below

@istest(seealldata=true)

public class DemoAccContTest {}


You can see the code coverage by going to code screen as shown below









Comments

Popular posts from this blog

The Salesforce Certification Frenzy: Balancing Quantity with Quality in a Changing Market

The Ultimate Guide to Building a Salesforce Career: Roles, Skills, and Strategies for Success