function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
nitin sharma 366nitin sharma 366 

Test class is written and I need advice to know if Test code is fine or not

Hi Everbody,

I have AfterInsert Trigger on Opportunity object so when an opportunity is inserted ,task should be automatically created and associated with that opportunity.Trigger is working fine and now I have written test class for the trigger which is given below.I need to know if I can write better test class or below given class is fine.

Secondly,How do I test for exceptions in the code.How do I fail records in the tests class to ensure that test class is covering all the scenarios.

Two things needs to be tested.
1)Successful bulk insertion of records
2)Failed records .


Please advice.

@isTest
public class TaskCreation {
     @isTest static void TestTaskcreation()
     {
         list<opportunity>OppRecords=new list<opportunity>();
         
         for(integer i=0;i<200;i++)
         {
             
         Opportunity opp=new opportunity();
         opp.Name='New opportunity';
         opp.stagename='Prospecting';
         opp.Closedate=system.Today().addMonths(1);
         OppRecords.add(opp);
                     
         }
         
         //insert oppRecords;
                  
         
         List<opportunity>InsertedOpps=new list<opportunity>([select id from opportunity where id in:oppRecords]);
         
         List<task>TaskTobeInserted=new list<task>();
             
        for(opportunity Fetched:InsertedOpps) 
        {
            
            Task t=new task();
            t.subject='New task has been created for new opportunity';
            t.whatid=Fetched.id;
            TaskTobeInserted.add(t);
                        
        }
         
         insert TaskTobeInserted; 
         
     
         Test.startTest();
      
         Database.SaveResult[] result= Database.Insert(oppRecords,false);
               
         set<id>SuccessfullOppIds=new set<id>();   
        
         for(Database.SaveResult sr : Result)
         {
         If(sr.isSuccess())
         {
                          
             SuccessfullOppIds.add(sr.getId());
             
         } 
             
         }
            for(list<task>r:[Select id,subject from task where whatid in:SuccessfullOppIds])
             { 
             for(Task CheckSubject:r)
             {
             
                                  
                 System.assertEquals('New task inserted on Opportunity creation',CheckSubject.subject);
             }

             }    
         
         
             
         
         Test.stopTest();
     }
    
}