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

Test Class code coverage not increasing

Hi All,
i have wrote the trigger and now i am writting test class for this  but code coverage is going only 67%, Please help me to increase the code coverage:
Here is the trigger:
trigger deleteandedittask on Task (before delete, before update) {
  string rtypeid = [Select id,Name from RecordType where  sObjectType='Task' and isActive=true and Name = 'FA-CRM System Task'].id;
  set<Id> bypassProfileIdSet = new Set<id>();  
  bypassProfileIdSet.add(RoleProfile__c.getInstance('API Users').ID__c);
  bypassProfileIdSet.add(RoleProfile__c.getInstance('System Administrator').ID__c);
        for (task t : Trigger.New)  
            String strwhatId = ''; String strwhoId = '';
            If(t.whatid != null)strwhatid = String.valueOf(t.Whatid).substring(0 , 3);
            If(t.whoid != null) strwhoid = String.valueOf(t.Whoid).substring(0 , 3);
           if(strwhatid == '001' || strwhoid== '003' && t.whatid==null )
            if( Trigger.oldMap.get( =='Completed')  
                if(t.RecordTypeId == rtypeid)
                    if(Trigger.oldMap.get( != Trigger.newmap.get(
                    t.Status.addError('Cannot edit or delete Activity History.');
                    if(Trigger.oldMap.get( != Trigger.newmap.get(
                    t.Priority.addError('Cannot edit or delete Activity History.');
                    if(Trigger.oldMap.get( != Trigger.newmap.get(
                    t.Subject.addError('Cannot edit or delete Activity History.');
                    if(Trigger.oldMap.get( != Trigger.newmap.get(
                    t.Ownerid.addError('Cannot edit or delete Activity History.');
                    t.addError('Cannot edit or delete Activity History'); 
                t.addError('Cannot edit or delete Activity History');   
         for (task t : Trigger.old) 
           String strwhatId = ''; String strwhoId = '';
           If(t.whatid != null)strwhatid = String.valueOf(t.Whatid).substring(0 , 3);
           If(t.whoid != null) strwhoid = String.valueOf(t.Whoid).substring(0 , 3);
          if(strwhatid == '001' || (strwhoid== '003' && t.Whatid==null))
            if(( Trigger.oldMap.get( =='Completed')  ) { 
                            t.addError('Cannot edit or delete Activity History.');

And here is my test class:

private class Testdeleteandedittask {

  static testMethod void myUnitTest() {
        //Init and Creating data
        List<Profile> ProfileList=new List<Profile>();
        String Userrecord='FA-CRM Platform';
        Profile pro = [SELECT Id FROM profile WHERE name =:Userrecord];
        User u1 = new User(alias = 'TaskF', email='', emailencodingkey='UTF-8', lastname='TaskFormat', languagelocalekey='en_US',localesidkey='en_US', profileid = pro.Id,timezonesidkey='America/Los_Angeles', username='',LR_Firm_ID__c=2);
        insert u1;
        String rectype=[Select id,Name from RecordType where  sObjectType='Task' and isActive=true and Name = 'Advisor Tasks'].id;
        Map<String,RecordType> RecortypeMap=new Map<String,RecordType>(); 
            for(RecordType r:[select id,name from RecordType Where SobjectType = 'Account' and name='Person'])
           List<Account> AccountList=new List<Account>();
            Account acc1 = new Account(name='account1',Mailing_Line1__c='Line1',PrimaryPhoneType__c='Business',PrimaryPhone__c='5423534', PrimaryPhoneFormat__c='TEST', SecondaryPhoneFormat__c='TEST');
            Account acc2 = new Account(name='account2',Mailing_Line1__c='Line2',PrimaryPhoneType__c='Business',PrimaryPhone__c='5423534', PrimaryPhoneFormat__c='TEST', SecondaryPhoneFormat__c='TEST');
            insert AccountList;
         Profile[] Pr = [Select id from PRofile limit 2];
            RoleProfile__c obj1 = new RoleProfile__c();
            obj1.Name  = 'API Users';
            obj1.ID__c = PR[0].id;
            obj1.Type__c = 'Profile';
            Insert obj1;
            RoleProfile__c obj2 = new RoleProfile__c();
            obj2.Name  = 'System Administrator';
            obj2.ID__c = PR[1].id;
            obj2.Type__c = 'Profile';
            Insert obj2;
            List<Task> tasklist = new List<Task>();
            for(integer i=0;i<5;i++){
            Task task = new Task();
            task.Status='In Progress';
            task.subject='sw test'+i;
            Task task1 = new Task();
                task1.Status='In Progress';
                task1.subject='sw test'+7;
            insert task1; 
            Task task2 = new Task();
                task2.Status='In Progress';
                task2.subject='sw test'+8;
            insert task2;
            task2.subject='sw test'+9;
            update task2; 
          //  tasklist.add(task);
            insert tasklist;
            List<Event> Eventlist = new List<Event>();
            for(integer i=0;i<5;i++){
            Event event = new Event();
            event.EndDateTime = System.Now()+10;
            event.StartDateTime = System.Now()+10;
            event.subject='ev test'+i;
            insert eventlist;
            Event event2 = new Event();
            event2.EndDateTime = System.Now()+10;
            event2.StartDateTime = System.Now()+10;
            event2.subject='ev test'+7;
            insert event2;
            List<Event> NewEventlist = new List<Event>();
            for(Event ev23:eventlist){
                ev23.Comments__c='Closed in Update ';
            update NewEventlist;
            List<Task> TaskListForupdateDelete=new List<Task>(); 
            List<Event> eventListForupdateDelete=new List<Event>();  
            for(Task t:[select id,RecordTypeId,Status,Whatid,Subject from Task where id in:taskList ])
                t.RecordTypeId= rectype;
                t.status='Completed' ;
                t.subject='sw Etest';
           // system.assertEquals(TaskListForupdateDelete[0].Whatid,AccountList[0].id );
            for(Event e:[select id,Whatid,Subject,StartDateTime,EndDateTime from Event where id in:EventList ])
            system.assertEquals(EventListForupdateDelete[0].Whatid,AccountList[0].id );
            update TaskListForupdateDelete; 
              delete task1;
              delete event2;
Since writing a test class to cover all of the facets of this class is not something that anyone on here will do for you, I can give you some pointers and hopefully get you started.  I would recommend that you do some reading on testing [1] [2] [3] [4] to get a better understanding.  Each of your individual tests should only tests one specific portion of you class (ie a constructor test, sendEmail test, contactSelected test, etc).  You should also have both a postitive (everything works perfectly) and a negative (things are not right) test.

I would also recommend that you split your current test into several parts instead of trying to test all the facets in one monolithic test method.  I see at least three different test methods in your current single test method

Each test should follow the following structure:
  • Setup of test data. This includes creation of any data needed by your class.  Account, Contacts etc
  • Starting the test. This is calling Test.startTest() to reset the governor limits
  • Calling your class / method
  • Stopping the test.This is calling Test.stopTest() to reset the governor limits and allow for any async jobs to finish
  • Asserting that your changes have worked
    • If you have inserted/updated/deleted data, you need to query for the updates
    • Run System.assert, System.assertEquals, System.assertNotEquals to verify that you got the correct data back
If you have any specific problems with your tests, feel free to create a new post or update this post with the part of the class you are trying to test and your current test method, and you will more likely get a better response then asking for someone to essentially write an entire test class for you.

NOTE: Please use the "Add a code sample" button (icon <>) when adding code to increase readability and referenceability.