I am new to triggers. I will admit that but this is my first trigger and I really want it to work! My problem is that I still am receiving only 70% Code Coverage when the trigger works fine in sandbox but when I click into each one of these colored lines below I receive the same Duplication error. Thank you all ahead of time.
Duplication Error: To get this error message to display I doubeclicked on top of one of the line numbers. Is that the proper way to display what is wrong?
Trigger with Code Coverage Issues Highlighted:
Trigger minus Highlights
trigger checkForCompetitors on Opportunity (before update) {
Set<Id> closedLostOppIds = new Set<Id>();
Set<Id> oppsHavingCompetitors = new Set<Id>();
// fetch all the Opportunity Id's that have been closed
for(Opportunity opp : trigger.new)
{
if(trigger.OldMap.get(opp.Id).StageName != 'Closed Lost'
&& (opp.StageName == 'Closed Lost') && (opp.Reasons_for_Lost_Opportunity__c.contains('Competition')))
{
closedLostOppIds.add(opp.Id);
}
}
// fetch Opportunity Id's that have been Closed Lost and have a Competitor
for(OpportunityCompetitor oc : [Select OpportunityId From OpportunityCompetitor Where OpportunityId IN : closedLostOppIds ])
{
oppsHavingCompetitors.add(oc.OpportunityId);
}
// compare the two sets (one has Closed Lost opportunity id's and other has Closed Lost opps having a competitor)
// Left out opp's should not be allowed to close, so we throw an error.
for(Opportunity o : trigger.new)
{
if(closedLostOppIds.contains(o.Id) && !oppsHavingCompetitors.contains(o.Id))
o.addError('At least one competitor is required before closing this Opportunity');
}
}
Test Class
@isTest
private class Test_checkForCompetitors {
static testMethod void checkForCompetitors() {
// Create a test account
Account testAcct = new Account (Name = 'My Test Account');
insert testAcct;
// Create a test opportunity
Opportunity testOpp = new Opportunity( Name = 'My Test Opp1',
AccountId = testAcct.Id,
StageName = 'Closed Lost',
CloseDate = System.today(),
Reasons_for_Lost_Opportunity__c = 'Competition',
Next_Steps__c = 'This is only a Test',
LeadSource = 'Web Lead',
Purchase_Cadence__c = 'Annualized');
insert testOpp;
// Get the opportunity, verify the stage name and close date
testOpp = [SELECT StageName, Name, CloseDate, Reasons_for_Lost_Opportunity__c, Next_Steps__c, LeadSource, Purchase_Cadence__c
FROM Opportunity
WHERE id = :testOpp.Id];
System.assertEquals(testOpp.StageName, 'Closed Lost');
System.assertEquals(testOpp.Name, 'My Test Opp1');
System.assertEquals(testOpp.CloseDate, System.today());
System.assertEquals(testOpp.Reasons_for_Lost_Opportunity__c, 'Competition');
System.assertEquals(testOpp.Next_Steps__c, 'This is only a Test');
System.assertEquals(testOpp.LeadSource, 'Web Lead');
System.assertEquals(testOpp.Purchase_Cadence__c, 'Annualized');
}
}