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
Kathryn BullockKathryn Bullock 

Help - writing a test class for a trigger to prevent duplicate Opportunities

I new to Apex, and failing miserably.  Time and time again and I cannot come up with anything beyond 0% code coverage.  I have the following trigger:
trigger leadDuplicatePreventer on opportunity(before insert) {
   set<string> settgs = new set<string>();
   list<opportunity> opps = [select id,Trigger_Help__c  from opportunity WHERE CreatedDate = LAST_N_DAYS:90];
   Profile p=[SELECT ID, Name FROM Profile WHERE Id=:userinfo.getProfileId() Limit 1];
   for(opportunity opp : opps){
     if(opp.Trigger_Help__c != null && p.Name <> 'System Administrator'){
	 settgs.add(opp.Trigger_Help__c);
	 }
   }
   
   for(opportunity op : trigger.new){
      if(settgs.contains(op.Trigger_Help__c)){
	     op.adderror('An Opportunity of this type already exists on this Account.  Please contact a system administrator with questions.');
	  }
   
   }


   
}

The Trigger_Help__c is a formula field that combines Oppty_Type__c+Account Id.  These 9 lines are all I have to figure out and I cannot get this for the life of me.  My current test class is as follows:

@isTest
private class TestleadDuplicatePreventer {
    @isTest static void TestleadDuplicatePreventerwithOneOpp() {
    Account acct = new Account(Name='Test Account');
    insert acct;
    Opportunity opp = new Opportunity(Name=acct.Name + ' Opportunity',
                                     StageName='Open Opportunity',
                                     CloseDate=System.today().addMonths(1),
                                     Facility__c='Tacoma WA',
                                     Oppty_Type__c='UCO Service',
                                     AccountID=acct.Id);
    insert opp;
    Test.startTest();
    opp= new Opportunity(Name='Opportunity Test',
                        StageName='Open Opportunity',
                        CloseDate=System.today().addMonths(2),
                        Facility__c='Tacoma WA',
                        Oppty_Type__c='UCO Service',
                        AccountId=acct.Id);
    try
    {
        insert opp;
    }
    catch(Exception duplicate)
    {       
       System.assertEquals('An Opportunity of this type already exists on this Account.  Please contact a system administrator with questions.', duplicate.getMessage());
    }
    //this should probably be in a separate test method
    Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
  User u2 = new User(Alias = 'newUser', Email='newuser@testorg.com',
     EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
     LocaleSidKey='en_US', ProfileId = p.Id,
     TimeZoneSidKey='America/Los_Angeles', UserName='newuser@testorg.com');

  System.runAs(u2) {
      insert opp;
  }
        Test.stopTest();}}
But I have also been trying and failing with the following test class:
 
@isTest
public class TestleadDuplicatePreventer {
    static testMethod Void TestleadDuplicatePreventerwithOneOpp() {
        User u1 = [SELECT Id FROM User WHERE Alias='jmilt'];
        System.runAs(u1){
        Account acct = new Account(Name='Test Account');
        insert acct;
        Opportunity opp1 = new Opportunity(Name=acct.Name + ' Opportunity',
                                         StageName='Open Opportunity',
                                         CloseDate=System.today().addMonths(1),
                                         Facility__c='Tacoma WA',
                                         Oppty_Type__c='UCO Service',
                                         AccountID=acct.Id);
        Opportunity opp2 = new Opportunity(Name=acct.Name + ' Opportunity1',
                                          StageName='Open Opportunity',
                                          CloseDate=System.today().addMonths(1),
                                          Facility__c='Tacoma WA',
                                          Oppty_Type__c='UCO Service & Indoor Equipment',
                                          AccountID=acct.Id);
        Opportunity opp3 =  new Opportunity(Name=acct.Name + ' Opportunity2',
                                           StageName='Open Opportunity',
                                           CloseDate=System.today().addMonths(1),
                                           Facility__c='Tacoma WA',
                                           Oppty_Type__c='Trap Service',
                                           AccountID=acct.Id);
            Opportunity[] opps = new Opportunity [] {opp1, opp2, opp3};
            insert opps;
            
        Opportunity dup1 = new Opportunity(Name='Check',
                                          StageName='Open Opportunity',
                                          CloseDate=System.today().addMonths(1),
                                          Facility__c='Tacoma WA',
                                          Oppty_Type__c='UCO Service',
                                          AccountID=acct.Id);
            Test.startTest();
        try
        {
            insert dup1;
        }
        catch(Exception duplicate)
        {    
            System.assertEquals('An Opportunity of this type already exists on this Account.  Please contact a system administrator with questions.', duplicate.getMessage());

        }}
   Test.stopTest(); }

}

If anyone is out there who can help it would be greatly appreciated!
Best Answer chosen by Kathryn Bullock
Raj VakatiRaj Vakati
Use this code
 
@isTest
public class TestleadDuplicatePreventer {
    static testMethod Void TestleadDuplicatePreventerwithOneOpp() {
        // Create a unique UserName
        String uniqueUserName = 'standarduser' + DateTime.now().getTime() + '@testorg.com';
        // This code runs as the system user
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
        User u = new User(Alias = 'standt', Email='standarduser@testorg.com',
                          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
                          LocaleSidKey='en_US', ProfileId = p.Id,
                          TimeZoneSidKey='America/Los_Angeles',
                          UserName=uniqueUserName);
        
        System.runAs(u) {
            
            Account acct = new Account(Name='Test Account');
            insert acct;
            Opportunity opp1 = new Opportunity(Name=acct.Name + ' Opportunity',
                                               StageName='Open Opportunity', 
                                               CloseDate=System.today().addMonths(1),
                                               AccountID=acct.Id);
            Opportunity opp2 = new Opportunity(Name=acct.Name + ' Opportunity1',
                                               StageName='Open Opportunity', 
                                               CloseDate=System.today().addMonths(1),
                                               AccountID=acct.Id);
            Opportunity opp3 =  new Opportunity(Name=acct.Name + ' Opportunity2',
                                                StageName='Open Opportunity', ,
                                                CloseDate=System.today().addMonths(1),
                                                AccountID=acct.Id);
            Opportunity[] opps = new Opportunity [] {opp1, opp2, opp3};
                insert opps;
            
            Opportunity dup1 = new Opportunity(Name='Check',
                                               StageName='Open Opportunity', 
                                               CloseDate=System.today().addMonths(1),
                                               AccountID=acct.Id);
            Test.startTest();
            try
            {
                insert dup1;
            }
            catch(Exception duplicate)
            {    
                System.assertEquals('An Opportunity of this type already exists on this Account.  Please contact a system administrator with questions.', duplicate.getMessage());
                
            }}
        Test.stopTest(); }
    
}

 

All Answers

Raj VakatiRaj Vakati
Use this code
 
@isTest
public class TestleadDuplicatePreventer {
    static testMethod Void TestleadDuplicatePreventerwithOneOpp() {
        // Create a unique UserName
        String uniqueUserName = 'standarduser' + DateTime.now().getTime() + '@testorg.com';
        // This code runs as the system user
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
        User u = new User(Alias = 'standt', Email='standarduser@testorg.com',
                          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
                          LocaleSidKey='en_US', ProfileId = p.Id,
                          TimeZoneSidKey='America/Los_Angeles',
                          UserName=uniqueUserName);
        
        System.runAs(u) {
            
            Account acct = new Account(Name='Test Account');
            insert acct;
            Opportunity opp1 = new Opportunity(Name=acct.Name + ' Opportunity',
                                               StageName='Open Opportunity',Trigger_Help__c='Demo',
                                               CloseDate=System.today().addMonths(1),
                                               AccountID=acct.Id);
            Opportunity opp2 = new Opportunity(Name=acct.Name + ' Opportunity1',
                                               StageName='Open Opportunity',Trigger_Help__c='Demo',
                                               CloseDate=System.today().addMonths(1),
                                               AccountID=acct.Id);
            Opportunity opp3 =  new Opportunity(Name=acct.Name + ' Opportunity2',
                                                StageName='Open Opportunity',Trigger_Help__c='Demo',
                                                CloseDate=System.today().addMonths(1),
                                                AccountID=acct.Id);
            Opportunity[] opps = new Opportunity [] {opp1, opp2, opp3};
                insert opps;
            
            Opportunity dup1 = new Opportunity(Name='Check',
                                               StageName='Open Opportunity',Trigger_Help__c='Demo',
                                               CloseDate=System.today().addMonths(1),
                                               AccountID=acct.Id);
            Test.startTest();
            try
            {
                insert dup1;
            }
            catch(Exception duplicate)
            {    
                System.assertEquals('An Opportunity of this type already exists on this Account.  Please contact a system administrator with questions.', duplicate.getMessage());
                
            }}
        Test.stopTest(); }
    
}

 
Kathryn BullockKathryn Bullock
I recieve the error that the Trigger_help__c field is not writeable.  :(
GhanshyamChoudhariGhanshyamChoudhari
Hi  ,
 
@isTest public class TestleadDuplicatePreventer { 
    static testMethod Void TestleadDuplicatePreventerwithOneOpp() { 
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
        User u = new User(Alias = 'standt',
                          Email='standarduser@testorg.com',
                          EmailEncodingKey='UTF-8',
                          LastName='Testing',
                          LanguageLocaleKey='en_US',
                          LocaleSidKey='en_US',
                          ProfileId = p.Id,
                          TimeZoneSidKey='America/Los_Angeles',
                          UserName='standarduser@testorg.com');
        insert u;
        User u1 = [SELECT Id FROM User WHERE Email='standarduser@testorg.com'];
        System.runAs(u1){
            try{
                Account a = new Account(name='testacc'); 
                insert a; 
                opportunity opp = new opportunity();
                opp.AccountId=a.Id; 
                opp.Name='testopp';
                opp.Oppty_Type__c='Testtype'; 
                opp.CloseDate=system.today(); 
                opp.StageName='Qualification'; 
                insert opp; 
                opportunity opp2 = new opportunity(); 
                opp2.AccountId=a.Id; 
                opp2.Name='testopp';
                opp2.Oppty_Type__c='Testtypr';
                opp2.CloseDate=system.today(); 
                opp2.StageName='Qualification'; 
                insert opp2;
                
            }
            catch(Exception duplicate) 
            { System.assert(duplicate.getMessage().contains('An Opportunity of this type already exists'), true);
            }
        }
    }
}


Mark as best answer if it helps you.
Thanks,
Ghanshyam Choudhari
GhanshyamChoudhariGhanshyamChoudhari
no need to create Trigger_help__c  filed data becz it will create automatically once you will create opp with name and opp type
Raj VakatiRaj Vakati
If Trigger_help__c  is formula field, you need to set the data to populate the value into the formula  
Kathryn BullockKathryn Bullock
Thank you for all of your help!  I am still recieving 0% Code Coverage.  Maybe my trigger is all wrong??  I am so lost.
Kathryn BullockKathryn Bullock
This is the error of why it failed the test run:
System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_USERNAME, Duplicate Username.<br>The username already exists in this or another Salesforce organization. Usernames must be unique across all Salesforce organizations. To resolve, use a different username (it doesn't need to match the user's email address). : [Username]
Raj VakatiRaj Vakati
Use this code
 
@isTest
public class TestleadDuplicatePreventer {
    static testMethod Void TestleadDuplicatePreventerwithOneOpp() {
        // Create a unique UserName
        String uniqueUserName = 'standarduser' + DateTime.now().getTime() + '@testorg.com';
        // This code runs as the system user
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
        User u = new User(Alias = 'standt', Email='standarduser@testorg.com',
                          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
                          LocaleSidKey='en_US', ProfileId = p.Id,
                          TimeZoneSidKey='America/Los_Angeles',
                          UserName=uniqueUserName);
        
        System.runAs(u) {
            
            Account acct = new Account(Name='Test Account');
            insert acct;
            Opportunity opp1 = new Opportunity(Name=acct.Name + ' Opportunity',
                                               StageName='Open Opportunity', 
                                               CloseDate=System.today().addMonths(1),
                                               AccountID=acct.Id);
            Opportunity opp2 = new Opportunity(Name=acct.Name + ' Opportunity1',
                                               StageName='Open Opportunity', 
                                               CloseDate=System.today().addMonths(1),
                                               AccountID=acct.Id);
            Opportunity opp3 =  new Opportunity(Name=acct.Name + ' Opportunity2',
                                                StageName='Open Opportunity', ,
                                                CloseDate=System.today().addMonths(1),
                                                AccountID=acct.Id);
            Opportunity[] opps = new Opportunity [] {opp1, opp2, opp3};
                insert opps;
            
            Opportunity dup1 = new Opportunity(Name='Check',
                                               StageName='Open Opportunity', 
                                               CloseDate=System.today().addMonths(1),
                                               AccountID=acct.Id);
            Test.startTest();
            try
            {
                insert dup1;
            }
            catch(Exception duplicate)
            {    
                System.assertEquals('An Opportunity of this type already exists on this Account.  Please contact a system administrator with questions.', duplicate.getMessage());
                
            }}
        Test.stopTest(); }
    
}

 
This was selected as the best answer
Kathryn BullockKathryn Bullock
That worked beautifully and I now have 66%, which is enough for the trigger.  Now I have the problem of not being able to upload it to my production org.  It says there is 0%, but it was covered in the test!  What should I do now?