Friday, 9 February 2018

Apex Trigger with Helper Class and Test Class


For New Developer Like I am.

1. Scenario - Create a Class, when an Account is inserted then an Opportunity with pre-defined value will be inserted under Account (Related List).

2. Create a Trigger for call the Class functionality.

3. Also create a Test Class.

Step 1. Class - 'CreateAccountOpportunity'

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public class CreateAccountOpportunity {
public List <opportunity> oppList = new List <opportunity>();

public void CreateOpportunity(List <account> accList){
 for (Account objAcc: accList) {
  Opportunity objOpp = new Opportunity();
  objOpp.AccountID = objAcc.ID;
  objOpp.Name = a.Name;
  objOpp.CloseDate = System.Today().addDays(3);
  objOpp.StageName = 'Prospecting';
  oppList.add(objOpp);
 }
  if (oppList.size() > 0)
  Database.Insert(oppList);
 }
}

Step 2. Trigger - 'trg_createnewoppor'

1
2
3
4
5
6
trigger trg_createnewoppor on Account(after Insert, after update) {
 if ((Trigger.isInsert) || (Trigger.IsBefore)) {
  CreateAccountOpportunity objAccOpp = new CreateAccountOpportunity();
  objAccOpp.CreateOpportunity(Trigger.New);
 }
}

Step 3. Test Class - 'trg_createnewoppor'

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
@isTest
public class CreateNewOpportunityTest {
  @isTest
  public static void CreateOpportunityTestMethod() {
    Account objAccount = new Account();
    objAccount.Name = 'Test Acc';
    insert objAccount;
    System.AssertEquals(objAccount.Name, 'Test Acc');

    Opportunity objOpportunity = new Opportunity();
    objOpportunity.Name = 'Test Opp';
    objOpportunity.Accountid = objAccount.id;
    objOpportunity.StageName = 'Prospecting';
    objOpportunity.CloseDate = system.Today() + 3;
    insert objOpportunity;
    System.AssertEquals(objOpportunity.Name, 'Test Opp');
  }
}

In my next Blog I'll tell you some tips for Test Classes that I know, So don't forget to Follow me.
Thanks for Learn Carefully

Thanks & Regard.

No comments:

Post a Comment

Total Pageviews