ActionPlanTemplate apt = new ActionPlanTemplate();
apt.Name = 'AP_Teamplate_Apex';
apt.ActionPlanType = 'Industries';
// You can provide any object here for which AP is Supported
apt.TargetEntityType = 'Account';
System.debug('before ActionPlanTemplate insert');
insert apt;
ActionPlanTemplateVersion aptv = [select Id, Status from ActionPlanTemplateVersion where Status = 'Draft' and
ActionPlanTemplateId = :apt.Id]
ActionPlanTemplateItem apti = new ActionPlanTemplateItem();
apti.ActionPlanTemplateVersionId = aptv.Id;
//apti.DisplayOrder = 1;
apti.Name = 'AP_Teamplate_Item_Apex';
apti.ItemEntityType = 'Task';
insert apti;
aptv.Status = 'Draft';
System.debug('before ActionPlanTemplateVersion update');
update aptv;
ActionPlanTemplateItemValue aptiv=new ActionPlanTemplateItemValue();
aptiv.ActionPlanTemplateItemId=apti.id;
aptiv.ItemEntityFieldName='Task.ActivityDate';
aptiv.Name= 'ActivityDate';
aptiv.ValueFormula =' StartDate + 360';
insert aptiv;
aptiv=new ActionPlanTemplateItemValue();
aptiv.ActionPlanTemplateItemId=apti.id;
aptiv.ItemEntityFieldName='Task.Priority';
aptiv.Name= 'Priority';
aptiv.ValueLiteral='Normal';
insert aptiv;
aptiv=new ActionPlanTemplateItemValue();
aptiv.ActionPlanTemplateItemId=apti.id;
aptiv.ItemEntityFieldName='Task.Subject';
aptiv.Name= 'Subject';
aptiv.ValueLiteral='New test task';
insert aptiv;
aptv.Status = 'Final';
System.debug('before ActionPlanTemplateVersion update');
update aptv;
System.debug([select Id, Name, Status from ActionPlanTemplateVersion]);
List<ActionPlanTemplateVersion> tempVerList = [select Id from ActionPlanTemplateVersion where Status = 'Final' limit 1];
System.assertEquals(1, tempVerList.size());
List<Account> accList = [select Id from Account limit 1];
System.assertEquals(1, accList.size());
ActionPlan ap = new ActionPlan();
ap.Name = 'Test AP for Test Coverage';
System.debug('Adding template version id as '+tempVerList.get(0).Id +' ----');
ap.ActionPlanTemplateVersionId = tempVerList.get(0).Id;
ap.ActionPlanType = 'Industries';
ap.TargetId = accList.get(0).Id;
ap.ActionPlanState = 'Not Started';
ap.StartDate = System.today();
System.debug('before ActionPlan insert'+ap + '----------');
insert ap;