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
Julia BakerJulia Baker 

Deploying triggers from sandbox to production: Code coverage failure

Trying to deploy development from my sandbox using change sets. Whilst custom fields, tabs etc come across fine, the triggers are failing with the following error:

Code Coverage Failure Your organization's code coverage is 0%. You need at least 75% coverage to complete this deployment. Also, the following triggers have 0% code coverage. Each trigger must have at least 1% code coverage.

This means nothing to me and I'm just getting more confused looking through the help documents. I don't really do code and I don't know where to start. Any help would be very much appreciated
Best Answer chosen by Julia Baker
Ankit Maini.Ankit Maini.
At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully. Note the following:
  • When deploying to a production organization, every unit test in your organization namespace is executed.
  • Calls to System.debug are not counted as part of Apex code coverage.
  • Test methods and test classes are not counted as part of Apex code coverage.
  • While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of code that is covered. Instead, you should make sure that every use case of your application is covered, including positive and negative cases, as well as bulk and single records. This should lead to 75% or more of your code being covered by unit tests.

Every trigger must have some test coverage.
All classes and triggers must compile successfully.
Source (http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_deploying_ant_deploy.htm)

Thanks
Ankit Maini

All Answers

PratikPratik (Salesforce Developers) 
Hi Julia,

To deploy the code(triggre, VF page, Apex class etc.) from Sandbox to Production, you need at least 75% test coverage.

Salesforce has concept of "test class" to have coverage. 

You can got through:
https://developer.salesforce.com/page/An_Introduction_to_Apex_Code_Test_Methods

http://www.sfdc99.com/2013/11/02/example-write-a-test-class-for-our-deduping-trigger/

If you have any question, please post so we can help!

Thanks,
Pratik
 
Ankit Maini.Ankit Maini.
At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully. Note the following:
  • When deploying to a production organization, every unit test in your organization namespace is executed.
  • Calls to System.debug are not counted as part of Apex code coverage.
  • Test methods and test classes are not counted as part of Apex code coverage.
  • While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of code that is covered. Instead, you should make sure that every use case of your application is covered, including positive and negative cases, as well as bulk and single records. This should lead to 75% or more of your code being covered by unit tests.

Every trigger must have some test coverage.
All classes and triggers must compile successfully.
Source (http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_deploying_ant_deploy.htm)

Thanks
Ankit Maini
This was selected as the best answer
Julia BakerJulia Baker
Thanks Pratik, Ankit and TechnozChamp

With a combination of all of the help documents you provided and a lot of fiddling around, I've finally got it sorted. Thanks for your replies and help!

Julia
Ankit Maini.Ankit Maini.
HI Julia,

Don't forget to mark your thread as 'SOLVED' with the answer that best helps you. 
Alex GopshteinAlex Gopshtein
Hello,

I tested my code in Sandbox (via test classes) and passed with 96%. I was then able to create Outboud Change Sets, and Inbound in Production. However the production didn't take my changes. It says "Code Coverage Failure. Your organization's code coverage is 0%" .

Please advise.
Thank you!
Alex
Ankit Maini.Ankit Maini.
Hi Alex,

I think your test case is getting fail in the production that is why code coverage failure is appearing. Please check and see if this is exactly happening.
Ankit Maini.Ankit Maini.
@Alex I would suggest you to use assert statements while writing the test cases if you have not written yet.
Yuri SingidasYuri Singidas
I have a similar issue with my before-delete trigger. Please help!

I got frustrated trying to deploy a simple before-delete trigger because it doesn't matter if the code coverage for the trigger is 40% in the sandbox (you only need 1% for triggers) because in production it always drops down to 0% and I cannot deploy it.

I ran all test classes in both production and sandbox environment and they have 94% and 84% code coverage, respectively. What went wrong? The trigger is so simple:

A. Trigger

trigger deleteAppeal on Appeal__c (before delete) 
  {
     Profile userProfile = [ SELECT Name FROM Profile WHERE Id = :UserInfo.getProfileId() ];
     if ( userProfile.Name <> 'SYSTEM ADMINISTRATOR' )
     {
        for ( Appeal__c appeal:trigger.old )
        {
           appeal.addError('You cannot delete an Appeal. Please ask your System Administrator to do it for you.');
        
        }
       
     }
    }

B. Test class:

@isTest
private class DeleteAppealTriggerTest
{   
    
    static testMethod void deleteAppealTest()
    {
          
    Case tmpDocket = new Case();
    tmpDocket.Date_Of_Claim__c = Date.newInstance( 2014, 4, 6 ); // MUST be a sunday for validation
    insert tmpDocket;

    Appeal__c tmpAppeal = new Appeal__c();
    tmpAppeal.Case__c = tmpDocket.Id;
            
        insert tmpAppeal;

        Test.startTest();
        
        try
        {
            delete tmpAppeal;
         }
         catch(Exception e) 
     {
         system.assertEquals('Appeal cannot be deleted.', e.getMessage());
         }

        Test.stopTest();

        
      }
    
    
}


HELP!!
 
Shrikanth LaxminarayanShrikanth Laxminarayan

A: Trigger

//Ray : On every Insert Opportunity, create a Opportunity Line Item Automatically
trigger CreateOLIonInsertOpp on Opportunity(After insert) {
  List < Opportunity_Line_Item__c > list_opportunity_line_item = new list < Opportunity_Line_Item__c > ();
  //for every new Opportunity inserted
  if (Trigger.IsInsert) {
    for (Opportunity vopportunity: [SELECT Id,Product_Name__c,Product_Pitched__c,Trial_Created__c,Trial_Created_date__c
        FROM Opportunity WHERE Id IN: trigger.New]) {
      //create a Product Map
      Map < String, Id > productMap = new map < String, Id > ();
      for (Product_Master__c vproduct: [select id, Name From Product_Master__c]) {
        productMap.put(vproduct.Name, vproduct.Id);
      }
      //check for a valid Product_Pitched__c 
      if (vopportunity.Product_Pitched__c != null) {
       system.debug('------------>>>>>>>For every product in OLI creation' + vopportunity.Product_Pitched__c);
       for (String singleProduct: vopportunity.Product_Pitched__c.split(';')) {
          system.debug('------------>>>>>> product' + singleProduct);
          if (productMap.containskey(singleProduct)) {
            system.debug('------------>>>>>>exists,');
            //create a line item in case of a Product_Pitched__c is found in Product_Master__c
            Opportunity_Line_Item__c vopportunity_line_item = new Opportunity_Line_Item__c();
            vopportunity_line_item.Opportunity__c = vopportunity.Id;
            vopportunity_line_item.Product_Name__c = productMap.get(singleProduct);
            if(vopportunity.Trial_Created__c == 'Yes') {
              vopportunity_line_item.Trial__c = true;
              vopportunity_line_item.Trial_Start_Date__c = vopportunity.Trial_Created_date__c !=null ? vopportunity.Trial_Created_date__c : DateTime.now();
            }
            system.debug('------------>>>>>> create a new opportunitylineitem' + vopportunity_line_item);
            list_opportunity_line_item.add(vopportunity_line_item);
          }
        }
      }
      // insert the newly created OLIs 
      if (list_opportunity_line_item.size() > 0) {
        insert list_opportunity_line_item;
      }
    }
  }
}

// Creates a product line item(custom child object on opportunity) with details of product. 

B. Test Class

@isTest
public class createOLIonOPPInsert_Test {
  public static testMethod void testolicreate() {
    Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
    user intuser = new User(Alias = 'standt', Email='standarduser@testorg.com', 
      EmailEncodingKey='UTF-8', LastName='Integration User', LanguageLocaleKey='en_US', 
      LocaleSidKey='en_US', ProfileId = p.Id, 
      TimeZoneSidKey='America/Los_Angeles', UserName='intuser@practo.com');
    insert intuser;

    system.runAs(intuser) {
        //List<Territory_Mapping__c> list_Territory_Name = [Select Id From Territory_Mapping__c Where Territory_Name__c = 'Rest of India' Limit 1];
        String strRecordTypeId = [Select Id From RecordType Where SobjectType = 'Opportunity' and Name = 'Ray ROI'].Id;


        Account newaccount = new Account(
          Name = 'test opp Jul 171435',
          Practice_Category__c =  'Clinic',
          Ray_Practice_ID__c = '171435',
          Is_Computer_Available__c = 'Don\'t Know',
          Is_Internet_Availabe__c = 'Don\'t Know',
          Is_Receiptionist_Available__c = 'Don\'t Know',
          Lead_Type__c = 'Unpaid',
          Primary_Contact__c = '8989787898',
          Country_Code__c = 'India Only'
        );
        insert newaccount;

        Opportunity newopp = new Opportunity(
          RecordTypeId = strRecordTypeId,
            //Prod '012280000011DFA', Test : 0120k0000004NvXAAU
          //opportunity_id, //RAY ROI
          Name =  'OPP-'+ System.today().format(),
          Accountid = newaccount.Id,
          Product_Name__c  = 'Ray',
          Product_Pitched__c = 'Ray CM Atom',
          Closedate = System.today() + 7 ,
          StageName = 'Trial'
        );
        insert newopp;
    }
  }
}

//Creates and acccount and opportunity with mandatory fields filled in and expectation is that it will activate trigger on insert.

Pls Help!! @ankit maini, others

alenacalalenacal
Trying to deploy a trigger and test class that deployed fine in the past.  I only made a very small change and now it is saying there is 0% coverage.

Test Class:

@isTest
public class AllActivitiesCounter 
{
    public static testmethod void testinsert()
      {

 Task task= new task();
task.Subject = 'Call (Completed)';
task.status='Completed';
//task.Whoid = '0033700000ND3ti';
task.Whoid = '0033700000ahaJX';
insert task;

Contact ct = new Contact();
//ct.ID   = '0033700000ND3ti';
ct.ID = '0033700000ahaJX';
ct.All_Actvities_Counter__c = 1;

        }
}

Trigger:

trigger UpdateAllContactActivities on Task (after update) {

set<ID> ContactIds= new Set<ID>();
for(Task tt:trigger.new){
if(tt.whoId!=null && string.valueof(tt.WhoId).startsWith('003')){
    if(tt.Subject.containsIgnoreCase('Call (Completed)') || tt.Subject.containsIgnoreCase('Call (Left Message)') || tt.Subject.containsIgnoreCase('Email:') ||tt.Subject.containsIgnoreCase('Call (No Answer)') || tt.Subject.containsIgnoreCase('Call (Incoming)') || tt.Subject.containsIgnoreCase('Email - &') || tt.Subject.containsIgnoreCase('LinkedIn') || tt.Subject.containsIgnoreCase('[Sendbloom]')){
        if(tt.Status.equals('Completed')){
            ContactIDs.add(tt.whoID);
        }
    }
}
}

if(ContactIds.isEmpty())
return;

 if(stoprecurssionupdate.runonce()){
    List<Contact> cnts= new List<Contact>();
    Integer number1=1;
    for(Contact ct:[select id, name, All_Actvities_Counter__c, AE_Activities_Counter__c, BDR_Activities_Counter__c from Contact where id in:Contactids]){
        if(ct.All_Actvities_Counter__c ==null)
        ct.All_Actvities_Counter__c=0;
        ct.All_Actvities_Counter__c=ct.All_Actvities_Counter__c+number1;
            if(userinfo.getProfileId().contains('00e00000006t1rl')){
                 if(ct.AE_Activities_Counter__c ==null)
                 ct.AE_Activities_Counter__c=0;
                 ct.AE_Activities_Counter__c=ct.AE_Activities_Counter__c+number1;
             }else{
                 ct.AE_Activities_Counter__c=ct.AE_Activities_Counter__c;
             }
             if(userinfo.getProfileId().contains('00e00000006t1rW')|| userinfo.getProfileId().contains('00e00000006t62x') || userinfo.getProfileId().contains('00e37000000JBqB')){
                 if(ct.BDR_Activities_Counter__c ==null)
                 ct.BDR_Activities_Counter__c=0;
                 ct.BDR_Activities_Counter__c=ct.BDR_Activities_Counter__c+number1;
             }else{
                 ct.BDR_Activities_Counter__c=ct.BDR_Activities_Counter__c;
             }
        cnts.add(ct);
    }
    if(cnts.size()>0)
    {
    update cnts;
    }
    }
}

Any ideas?