About

Edit photo

Thursday, February 16, 2017

APEX Test Classes - Examples



Apply @istest annotation to code.

Signature Characterisitics:

  • static --- test method must be a static
  • void  --- it should always no return type.
  • no parameters --- Don't use parameters.

Example:
@istest
public class myclass
{
     @istest private static void mytest() {...}
     //or
     private static void testmethod mytest() {...}
}


Test cannot do:

  • commit changes to DB.
  • Perform callouts to external systems.
  • send outbound messages.

SOQL cannot find pre-existing data, except

  • user
  • profile
  • organization
  • record type
But if use @istest(seealldata=true) annotation, can get data from all the objects.


Test Requirements:

  • Atleast 75% apext statement must be executed.
  • All apex triggers must be called
  • All apex tests must executed without any exceptions / exceeding governors. 

we use,

  • system.assert()
  • system.assertequals()
  • system.assertnotequals()
Note: i) pass upto 200 records only. ii) Don't depend on pre-existing data.

Imp: use Test.StartTest() and Test.StopTest()

Example:
I have 3 objects named, a, b, c. C is parent of B and A,  B is parent of A. A to B has Master, B to C has Master, A to C has lookup. I want to get the C name to my A where B's object is having C.

trigger afrombfromc on a__c (before insert, before update) {
 set<id> aID = new set<id>();
 set<id> bID = new set<id>();
 set<id> cID = new set<id>();
 
 for(a__c a1:trigger.new)
 {
  bID.add(a1.b_object__c);
 }
 
    map<id,b__c> map2;
    map<id,c__c> map3;
    
 if(!bID.isempty())
  map2 = new map<id,b__c>([select id, name, b_field__c, c_object__c from b__c where id in:bID]);
    
    for(b__c b:map2.values())
    {
        cID.add(b.c_object__c);
    }
    
    if(!cID.isempty())
  map3 = new map<id,c__c>([select id, c_field__c from c__c where id in:cID ]);
 
 for(a__c a1:trigger.new)
 {
  a1.b_field__c = map2.get(a1.b_object__c).b_field__c;
  //a1.c__c = map3.get(map2.get(a1.b_object__c).b_object__c).id;
  a1.c__c = map3.get(map2.get(a1.b_object__c).c_object__c).id;
 }/span>
}

Apex Test Class:

@istest public class afrombfromc_test {
 @istest public static void mytest1()
    {
        c__c c = new c__c();
        c.name = 'cname';
        insert c;
        b__c b = new b__c();
        b.name = 'bname';
        b.c_object__c = c.id;
        insert b;
        a__C a = new a__c();
        a.name = 'aname';
        a.b_object__c = b.id;
        insert a;
        a__c asoql = [select c__c from a__c where id=:a.id];
        system.assertEquals(asoql.c__c, c.id);
    }
}




0 comments:

Post a Comment