首页 > 解决方案 > Salesforce 中的触发器测试类

问题描述

标签: salesforceapex

解决方案


Not sure exactly what your requirements were for your project, you can probably get this done without code doing a rollup sum field that counts the opportunities tied to an account that has the type used in Trigger_Help__c and then put a validation on opportunity that when ISNEW() if Account.Count_Of_Type__c > 0 causes the validation to fire OR on opportunity create a hidden field that is unique that is the concatenation of the account id and the Opportunity type which can be set by workflow or the process builder. Tis would prevent duplicate types from being added for a given account.

But to your original question: In your test I dont see you set the Trigger_Help__c field unless that is set by automation. Also when creating your second opp you dont need to do the query of account you can just use the acct.Id from earlier in the code.

For your catch you need to assert that the e.getMessage() is the message you expect from your add error in the trigger.

You probably also need to do a separate where you runAs(admin_user) where admin_user is a user that you create with the System administrator profile to ensure that you dont get an error when you run as the admin user, along the lines of:

@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();
}

}​</p>


推荐阅读