Monday, April 24, 2023

What Is The Use Of SeeAllData In Test Class In Salesforce

Annotation IsTest(SeeAllData=true) opens up data access to records in your organization. The IsTest(SeeAllData=true) annotation applies to data queries but doesn't apply to record creation or changes, including deletions. New and changed records are still rolled back in Apex tests even when using the annotation.

// All test methods in this class can access all data.
@IsTest(SeeAllData=true)
public class TestDataAccessClass {
    // This test accesses an existing account. 
    // It also creates and accesses a new test account.
    static testmethod void myTestMethod1() {
        // Query an existing account in the organization. 
        Account a = [SELECT IdName FROM Account WHERE 
Name='Acme' LIMIT 1];
        System.assert(a != null);
        
     // Create a test account based on the queried account.
        Account testAccount = a.clone();
        testAccount.Name = 'Acme Test';
        insert testAccount;
        
        // Query the test account that was inserted.
        Account testAccount2 = [SELECT IdName 
FROM Account 
                          WHERE Name='Acme Test' LIMIT 1];
        System.assert(testAccount2 != null);
    }
    // Like the previous method, this test method can also 
access all data
    // because the containing class is annotated with 
@IsTest(SeeAllData=true).
    @IsTest static void myTestMethod2() {
        // Can access all data in the organization.
   }
}

The below second example shows how to apply the @IsTest(SeeAllData=true) annotation on a test method. Because the test method’s class isn’t annotated, you have to annotate the method to enable access to all data for the method. The second test method doesn’t have this annotation, so it can access only the data it creates. In addition, it can access objects that are used to manage your organization, such as users.


@IsTest
private class ClassWithDifferentDataAccess {

    // Test method that has access to all data.
    @IsTest(SeeAllData=true)
    static void testWithAllDataAccess() {
        // Can query all data in the organization.      
    }
    
// Test method that has access to only the data it creates
  // and organization setup and metadata objects.
    @IsTest static void testWithOwnDataAccess() {
        // This method can still access the User object.
        // This query returns the first user object.
        User u = [SELECT UserName,Email FROM User LIMIT 1]; 
        System.debug('UserName: ' + u.UserName);
        System.debug('Email: ' + u.Email);
        
      // Can access the test account that is created here.
        Account a = new Account(Name='Test Account');
        insert a;      
        // Access the account that was just created.
        Account insertedAcct = [SELECT Id,Name FROM Account 
                              WHERE Name='Test Account'];
        System.assert(insertedAcct != null);
    }
}


  • If a test class is defined with the @IsTest(SeeAllData=true) annotation, the annotation applies to all its test methods. The annotation applies if the test methods are defined with the @IsTest annotation or with the (deprecated) testMethod keyword.
  • The @IsTest(SeeAllData=true) annotation is used to open up data access when applied at the class or method level. However, if the containing class has been annotated with @IsTest(SeeAllData=true), annotating a method with @IsTest(SeeAllData=false) is ignored for that method. In this case, that method still has access to all the data in the organization. Annotating a method with @IsTest(SeeAllData=true) overrides, for that method, an @IsTest(SeeAllData=false) annotation on the class.
  • @IsTest(SeeAllData=true) and @IsTest(IsParallel=true) annotations cannot be used together on the same Apex method.

Thursday, April 20, 2023

Free Salesforce Certification Vouchers

Hello All,

Please leave your email id in the comment box or mail at sfdev52@gmail.com

The voucher will sent to your email id.

Free Salesforce Certified Associate Exam- Valid till Apr 30, 2023
$140 off on $200 Exam- Valid till June 30, 2023


Monday, April 17, 2023

How To Avoid Recursion in Apex Trigger

Recursion is the process of executing the same Trigger multiple times to update the record again and again due to automation. There may be chances we might hit the Salesforce Governor Limit due to Recursive Trigger.

To avoid these kind of situation we can use public class static variable.


In RecursiveTriggerHandler class, we have a static variable which is set to true by default.

public class RecursiveTriggerHandler{
     public static Boolean recursiveCheck = true;
}

In following trigger, we are checking if static variable is true only then trigger runs. Also we are setting static variable to false when trigger runs for first time. So if trigger will try to run second time in same request then it will not run.

trigger SampleTrigger on Contact (after update){
  Set<String> accIdSet = new Set<String>();
  if(RecursiveTriggerHandler.recursiveCheck){
      RecursiveTriggerHandler.recursiveCheck = false;
      for(Contact conObj : Trigger.New){
          if(conObj.name != 'SFDC'){
              accIdSet.add(conObj.accountId);
          }
      }
  }
}


1. Trigger runs, recursiveCheck variable value will be checked.
2. In the first run, variable will be true.
3. Then recursiveCheck variable value will be set to false.
4. Next time same IF condition will fail and recursion is stopped.

Thursday, April 13, 2023

Polymorphism in Apex Programming with Example

Polymorphism is a concept in object-oriented programming where a single method or function can be used to perform different operations based on the type of object that it is called on. In Apex, polymorphism can be achieved using interfaces, abstract classes, and virtual methods. Here's an example of polymorphism in Apex using interfaces:

// Define an interface
public interface Shape {
    void draw();
}


// Define classes that implement the Shape interface
public class Circle implements Shape {
    public void draw() {
        System.debug('Drawing a circle');
    }
}


public class Rectangle implements Shape {
    public void draw() {
        System.debug('Drawing a rectangle');
    }
}


// Call the draw method on different objects of type Shape
Shape s1 = new Circle();
Shape s2 = new Rectangle();
s1.draw(); // Output: Drawing a circle
s2.draw(); // Output: Drawing a rectangle

In the above example, we define an interface called Shape with a method called draw(). We then define two classes, Circle and Rectangle, that implement the Shape interface and provide their own implementation of the draw() method.

Finally, we create two objects of type Shape, one of type Circle and one of type Rectangle. When we call the draw() method on each of these objects, the appropriate implementation of the draw() method is called based on the type of the object, demonstrating polymorphism.


Let me know your thoughts in the comment section!!

Interfaces in Apex Programming with Example

In programming, an interface is a collection of abstract methods and constants that can be implemented by a class. Here are some uses of interfaces in programming:

Abstraction: Interfaces allow you to define a contract or a set of rules that must be followed by any class that implements the interface. This helps to separate the implementation details from the interface, making the code more modular and easier to maintain.

Polymorphism: Interfaces allow you to achieve polymorphism in your code. Since any class that implements the interface must provide an implementation for all of the methods in the interface, you can create objects of different classes that implement the same interface and treat them as if they were the same type.

Multiple Inheritance: In some programming languages, a class can only inherit from one parent class. However, a class can implement multiple interfaces, allowing it to inherit from multiple sources. This makes it easier to create complex class hierarchies without having to rely on multiple inheritance.

Lets understand the concept with the help of an example.

public interface Interest{
    Decimal calculatePaymentAmount();
}

In this example, we define an interface called Interest that has one method called calculatePaymentAmount(). Any class that implements the Interest interface must provide an implementation for the calculatePaymentAmount() method.

Here's an example of a class that implements the Interest interface:

public class HomeLoanPayment implements Interest {
    public Decimal calculatePaymentAmount() {
        // implement your logic
    }
}

In this example, the HomeLoanPayment class implements the Interest interface by providing an implementation for the calculatePaymentAmount() method. This method calculates the payment amount for a Home Loan.

By using an interface in this way, we can define a common set of methods that must be implemented by any class that implements the interface. This allows us to write more flexible and reusable code.


Where do we use Interfaces in Apex

Batch Apex: Developer needs to implement the Database.Batchable interface. Thats why we need to write three methods namely, Start, Execute and Finish.

Queueable Apex: In this scenario, developer needs to implement Queueable interface and implement the Execute method.


Let me know your thoughts in the comment section!!

Saturday, April 8, 2023

Static Variables and Static Methods in Apex

Static variables are variables that belong to an overall class, not a particular object of a class. Think of a static variable to be like a global variable – its value is shared across your entire org. Any particular object’s properties or values are completely irrelevant when using static. When a class containing static variables is first referenced, the static variables are initialized. The initialization process occurs only once per execution context, regardless of how many times the class is referenced.

This example illustrates static vs. non-static variables

public class classexmple {
  public Integer count = 0;
  public static Integer Scount = 0;
  public void executeMethod() {
    count = count + 1;
    Scount = Scount + 1;
  }
classexmple obj1 = new classexmple();
classexmple obj2 = new classexmple();
obj1.executeMethod();
obj2.executeMethod();
System.debug(obj1.count); // This is 1
System.debug(obj2.count); // This is 1
// Access static variables only by class name, 
not object name
System.debug(classexmple.Scount); // This is 2

Static methods, similarly, are methods that act globally and not in the context of a particular object of a class. Being global, static methods only have access to its provided inputs and other static (global) variables.

This example illustrates static vs. non-static methods

public class SecondExample {
  public void Method1() {
    // code
  }
  public static String Method2() {
    // code
    String a;
    return a;
  }
  public static String Method3(String param) {
    String a;
    //code
    return a;
  }
}

SecondExample obj = new SecondExample();
// Non-static methods require an object 
for context
obj.method1();
// Static methods aren't related to a 
particular object
// You don't even use an object to call a 
static method!
SecondExample.Method2();
SecondExample.Method3('value');


Let me know your thoughts in the comment section!!

Monday, April 3, 2023

What are Remote Site Settings in Salesforce

Salesforce allows you to access external website resources from a Salesforce application for your organization. You can access these external websites through Visualforce pages, Apex Callout, and via XmlHttpRequest calls. To avoid accessing malicious websites from Salesforce.com, the website first needs to be registered with remote site settings. Once the site is registered, it can be used within Salesforce.com. 

To Setup the Remote Site Setting 

  • search and click remote site settings in setup.site
  • Click on New Remote Site and enter the URL and other fields required.
  • Click Save.

Please find the description of the fields in remote site settings

site

Let me know your thoughts in the comment section!!

Mostly Viewed