+ 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.

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';
         //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';
         insert TaskTobeInserted; 
         Database.SaveResult[] result= Database.Insert(oppRecords,false);
         set<id>SuccessfullOppIds=new set<id>();   
         for(Database.SaveResult sr : Result)
            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);