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
Jon Goldberg 1Jon Goldberg 1 

Code Coverage 100%, Package Upload Fails

Hi All, 

Any help is appreciated, I am at wits end   I am new to creating triggers and test classes but I have managed to get my trigger to 100% code coverage. When I attempt to upload my package I am getting an error telling me the following:

One or more Apex triggers lack test coverage. Add test coverage for the following triggers and upload again:
createTripDestination


"createTrip Destination" is the trigger that shows 100% coverage.  I'm used the developer console to remove all test results, bring the coverage back to 0, and re-run the test classes, bringing my trigger back to 100%.

Has anyone seen this before?  It seems strange to me but I can't figure it out.
Tyler Mowbrey 1Tyler Mowbrey 1
Hi Jon,

Can you please post your trigger code and you test code? It would help in troubleshooting.

Tyler
Jon Goldberg 1Jon Goldberg 1
Hi Tyler, I would be happy to, just don't judge my spaghetti code :)  It works as a trigger but it was a definite first shot at one:

------------
Event trigger:
------------------------

trigger createTripDestination on Event (after insert, after update) {


  String userName = UserInfo.getUserName();
 String alias = [Select Alias From User where username = :userName].Alias;
     
     System.debug('STARTING RUN.... ');

     for (Event newEvent: Trigger.New)
         if (newEvent.Travel_Required__c == TRUE){      
  
             String myDate = String.valueOf(newEvent.ActivityDate);
             String tripName = myDate.split(' ', 0) +'-'+alias;
     
             Integer countTrips = [SELECT count() FROM Trip_Tracker__c where Trip_Tracker_Name__c =: tripName];
     
             if (countTrips == 0) {
                        System.debug('Creating Trip '+tripName); 
                        Trip_Tracker__c t = new Trip_Tracker__c(Trip_Tracker_Name__c= tripName, Travel_Date__c = newEvent.ActivityDate, Submit_Date__c = Date.Today() );
                        insert t;
                   } else {        
                         System.debug('Found Trip '+tripName); 
                   }
                   
                   
      //Create New Destination Record
      
          
          sObject id = [SELECT ID FROM Trip_Tracker__c where Trip_Tracker_Name__c =: tripName];
          ID myid = id.Id;
          
      //Get Account
          
          System.debug('Retrieving Account for Opportunity ' +newEvent.WhatId);
          String accName = [SELECT account.name from opportunity where id=:newEvent.WhatId].Account.Name;
          
          System.debug('Getting Account ID from Account Name '+accName);
          sObject AccId = [SELECT ID FROM Account where Name =: accName];
          ID myAccId = AccId.Id;
          
          System.debug('Inserting Destination');
           Trip_Destination__c d = new Trip_Destination__c(Opportunity__c = newEvent.WhatId, Appointment_Time__c = newEvent.StartDateTime, Appointment_End_Time__c = newEvent.EndDateTime, Destination_Purpose__c = newEvent.Subject);
           d.put('Trip_Name__c', myid);
           d.put('Account__c', myAccId);
           Database.SaveResult[] results = Database.insert(new SObject[] {d});        
           
     //Insert Trip Tracker Name on Event
                   
              } else {
                  System.debug('Travel Not Required, Abort...'); 
              }
     }

Test Class
---------------------

@isTest
private class createTripDestination
 {
    static testMethod void testCreateTripDestination () {
    String userName = UserInfo.getUserName();
    string alias = [Select Alias From User where username = :userName].Alias;
    
      Event newEvent = new Event(
             WhatId = '006o0000002tYLV',
            StartDateTime = datetime.now(),
            EndDateTime = datetime.now(),
            Subject = 'Test'
        );
             String tripName = '(2014-11-20)-jgold';     
             Integer countTrips = [SELECT count() FROM Trip_Tracker__c where Trip_Tracker_Name__c =: tripName];
     
             if (countTrips == 0) {
                        System.debug('Creating Trip '+tripName); 
                        Trip_Tracker__c t = new Trip_Tracker__c(Trip_Tracker_Name__c= tripName, Travel_Date__c = newEvent.ActivityDate, Submit_Date__c = Date.Today() );
                        insert t;
                   } else {        
                         System.debug('Found Trip '+tripName); 
                   }
                   
          sObject id = [SELECT ID FROM Trip_Tracker__c where Trip_Tracker_Name__c =: tripName];
          ID myid = id.Id;
          
            String oppty = '006o0000002tYLV';
            System.debug('SELECT ' +account.name + ' from opportunity where id '+oppty);
            System.debug('SELECT account.name from opportunity where id=:oppty].Account.Name');
            String accName = 'AB Partners, Inc.';
            System.debug('accName ='+accName);
            ID myAccId = '001o0000003a6o9';
          

         System.debug('Inserting Destination');
           Trip_Destination__c d = new Trip_Destination__c(Opportunity__c = newEvent.WhatId, Appointment_Time__c = newEvent.StartDateTime, Appointment_End_Time__c = newEvent.EndDateTime, Destination_Purpose__c = newEvent.Subject);
           d.put('Trip_Name__c', myid);
           d.put('Account__c', myAccId);
            Database.SaveResult[] results = Database.insert(new SObject[] {d});        

    }

}
 
Tyler Mowbrey 1Tyler Mowbrey 1
Hi Jon,

When creating test classes, you typically do not have access to your existing data. You would have to have @IsTest(SeeAllData=TRUE) at the top of your method. THIS IS NOT BEST PRACTICE AND NOT RECOMMENDED IF AVOIDABLE.

Ultimately, when running test cases, anything done to the database is erased at the completion of the test. Think of it as if you are starting with a brand new database that contains your data model (it also includes users which is great!). At the beginning of the test, you need to populate your database.

So you would do something similar to:

Account acc = new Account(Name='Test Account');
insert acc;

Contact con = new Contact(AccountId=acc.id,FirstName='Test',LastName='Contact');
insert con;

You can now do:

List<Contact> conList = [SELECT Id FROM Contact];
system.assertEquals(1, conList.size()); //Result is true because we only have one contact in the database.

All you need to do to get your test to start working is create your initial dataset.

Please feel free to let me know if I can help further/you have more questions.

Tyler
Jon Goldberg 1Jon Goldberg 1
Hi Tyler,

Thanks so much for your help, this is really starting to make more sense now.  I have re-written my test class assuming an empty DB at time of run, this has resulted in what I believe to be progress.

Now, however, even though my trigger shows 100% coverage, I am getting an error on package upload telling me: Average test coverage across all Apex Classes and Triggers is 21%, at least 75% test coverage is required.

This is strange to me, as I only care about this one test class, not anything else in the environment I am operating.  Do you have any idea how this can be happening?

Here is the new test class I am using:
-----------------------------------------------

@isTest

private class createTripDestinationEmptyDB

 {

    static testMethod void createTripDestinationEmptyDB () {

    String userName = UserInfo.getUserName();

    string alias = [Select Alias From User where username = :userName].Alias;

 

 System.debug('Creating Account');  

  List<Account> aList = new List<Account> {

       new Account (Name = 'My Test Account')

   };

  insert aList;

  System.debug('Account ID = ' + aList[0].id); 

   // Create a test opportunity

   System.debug('Creating Opportunity'); 

   List<Opportunity> oList = new List<Opportunity> {

     new Opportunity(Name ='My Test Oppty',

                        AccountID = aList[0].id,

                        Amount = 3000,

                        StageName = 'Needs Analysis',

                        CloseDate = System.today()

                    )

  };

  insert oList;

  System.debug('Opportunity ID = ' + oList[0].id); 


// Create a test event

    List<Event> eList = new List<Event> { 

          new Event(Subject = 'Test',

          ActivityDate = System.today(),

        StartDateTime = datetime.now(),

        EndDateTime = datetime.now(),

          WhatId = oList[0].id

      )           

    };

  insert eList;

             String tripName = '(2015-01-15)-JGold';     

             Integer countTrips = [SELECT count() FROM Trip_Tracker__c where Trip_Tracker_Name__c =: tripName];

         if (countTrips == 0) {

                        System.debug('Creating Trip '+tripName); 

                        Trip_Tracker__c t = new Trip_Tracker__c(Trip_Tracker_Name__c= tripName, Travel_Date__c = eList[0].ActivityDate, Submit_Date__c = Date.Today() );

                        insert t;

                   } else {        

                         System.debug('Found Trip '+tripName); 

                   }

                   
          sObject id = [SELECT ID FROM Trip_Tracker__c where Trip_Tracker_Name__c =: tripName];

          ID myid = id.Id;
  
            String oppty = oList[0].id;

            System.debug('SELECT ' +account.name + ' from opportunity where id '+oppty);

            System.debug('SELECT account.name from opportunity where id=:oppty].Account.Name');

            String accName = aList[0].Name;

            System.debug('accName ='+accName);

   ID myAccId = aList[0].id;

         System.debug('Inserting Destination');

           Trip_Destination__c d = new Trip_Destination__c(Opportunity__c = eList[0].WhatId, Appointment_Time__c = eList[0].StartDateTime, Appointment_End_Time__c = eList[0].EndDateTime, Destination_Purpose__c = eList[0].Subject);

           d.put('Trip_Name__c', myid);

           d.put('Account__c', myAccId);

           Database.SaveResult[] results = Database.insert(new SObject[] {d});        

   }

}
Tyler Mowbrey 1Tyler Mowbrey 1
Hi Jon,

Unfortunately while you only care about this class, Salesforce.com cares about all classes/triggers accross the organization. While this class may be 100%, the total accross all classes/triggers is 21%. You must have at least 75% coverage accross all classes/triggers to be able to deploy to production. Make sure to run all tests (Developer Console --> Test --> Run All) and check which classes/triggers still need test coverage.

Let me know if you need help with anything else.

Tyler