New to writing Apex Triggers and I tried to take it from my Sandbox to production but it said I need to get coverage on the Apex Trigger I have written. I tried going through some of the start off documents but I can't really find anything that is of help.

Can you all help me out? I have the Apex Trigger below.

trigger CreateRenewalOpportunityNewBusiness on Opportunity (after update, after insert) {
List<Id> opps = new List<Id>();

for( Opportunity opp : Trigger.new ) {

    if( ( opp.StageName != 'Closed Won' ) ||
        ( Trigger.isUpdate && (Trigger.oldMap.get(opp.Id).StageName == opp.StageName ) ) ) {

    if( ( opp.Has_Renewal__c != True ) ) {

    opps.add( opp.Id );

Map<Id,Opportunity> oppsMap = new Map<Id,Opportunity>( [SELECT Id, Amount, Account.Id, CloseDate, OwnerId, Account.Name, Account.Renewal_Date__c, RecordTypeId from Opportunity where Id IN :opps] );

List<Opportunity> renewalOpps = new List<Opportunity>();

for( Opportunity opp : oppsMap.values() ) {
    Opportunity renewalOpp = new Opportunity();

    Date closeDate = opp.CloseDate;

    String renewalDateString = '' + renewalDate;
    renewalDateString = renewalDateString.substring(0, renewalDateString.indexOf(' '));

    renewalOpp.CloseDate = opp.Account.Renewal_Date__c;
    renewalOpp.OwnerId = opp.OwnerId;
    renewalOpp.AccountId = opp.AccountId;
    renewalOpp.Amount = opp.Amount;
    renewalOpp.StageName = 'Id. Decision Maker';
    renewalOpp.RecordTypeId = '012c00000008iek';
    renewalOpp.Name = opp.Account.Name + ' > Renewal';
    renewalOpp.Type = 'Renewal';
    renewalOpp.Original_Opportunity__c = opp.Id;


insert renewalOpps;


  • 1
    n.b. using hard-coded ids for recordTypeId can be dangerous if your dev sandbox created the recordType before it was created in PROD. Best practice is to either fetch recordtypeids one-time via SOQL or to get from Schema.describe if you're up against SOQL limits
    – cropredy
    Commented Dec 23, 2013 at 23:08

1 Answer 1


Create a test class that does updates and inserts on Opportunity. Once the class is "test" then all the triggers fire are "test". Insert enough test data cases to exercise all of the code in the trigger. Use the @isTest annotation to define the class as test is the easiest.

  • 1
    As an aside, it's better practice to move your logic outside of the trigger and into a static class method that's called from the trigger. That way code coverage will be much easier to obtain, and your code will be much more testable.
    – Cdn_Dev
    Commented Dec 23, 2013 at 23:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .