+ Start a Discussion
Devendra Hirulkar 3Devendra Hirulkar 3 

how to write test class of trigger

hellow all
i dont no how to write a test class of trigger please help me and tell the test class of below trigger
thankss
here is my trigger 

trigger CopyRolltoStudent1 on class__c (before insert,before update) //You want it on update too, right?
{
  Map<ID, Student__c> parentroll = new Map<ID, Student__c>(); //Making it a map instead of list for easier lookup
  List<Id> listIds = new List<Id>();

  for (class__c childObj : Trigger.new)
  {
    listIds.add(childObj.student__c);
  }

  //Populate the map. Also make sure you select the field you want to update, Rollno
  //The child relationship is more likely called Classes__r (not Class__r) but check
  //You only need to select the child classes a if you are going to do something for example checking whether the Classes in the trigger is the latest
  parentroll = new Map<Id, Student__c>([SELECT id, Roll_No__c,(SELECT ID, Roll_No__c FROM Class__r) FROM Student__c WHERE ID IN :listIds]);

  for (class__c cl : Trigger.new)
  {
     Student__c myParentroll = parentroll.get(cl.student__c);
     myParentroll.Roll_No__c = Decimal.valueOf(cl.Roll_No__c);
  }
    
  update parentroll.values();
}
Best Answer chosen by Devendra Hirulkar 3
John PipkinJohn Pipkin
Devendra, 

Here is a basic framework of what your class should do:
 
Student__c student = new Student__c(/*add in fields and values*/);

insert student;

class__c newClass = new class__c(student__c = student.Id, Roll_No__c= 2.5,/*other fields*/);

test.startTest();

insert newClass;

test.stopTest();

student__c upd_student = [Select Id,Roll_No__c  from student__c where id = :student.Id];
system.assertEquals(2.5, upd_student.Roll_No__c );

Hope that helps. 

All Answers

John PipkinJohn Pipkin
Devendra, 

Here is a basic framework of what your class should do:
 
Student__c student = new Student__c(/*add in fields and values*/);

insert student;

class__c newClass = new class__c(student__c = student.Id, Roll_No__c= 2.5,/*other fields*/);

test.startTest();

insert newClass;

test.stopTest();

student__c upd_student = [Select Id,Roll_No__c  from student__c where id = :student.Id];
system.assertEquals(2.5, upd_student.Roll_No__c );

Hope that helps. 
This was selected as the best answer
Devendra Hirulkar 3Devendra Hirulkar 3
hi john 
thanku for solving my problem