Apex触发器的测试类在插入新案例之前已打开

问题描述 投票:0回答:1

我是Apex开发的新手。

我想为我的Apex触发器编写一个TestClass,该案例将案例与联系人和客户相关联。

我正在与您分享我的代码。有人可以帮我吗

trigger CaseBeforeInsert on Case (before insert) { 
    Set<String> relatedAccountsHIDs = new Set<String>();
    Set<String> relatedContactsEmails = new Set<String>();
    Map<String, Account> relatedAccounts = new Map<String, Account>();
    Map<String, Contact> relatedContacts = new Map<String, Contact>();

    //identify cases with related accounts & contacts
    for(Case cs: Trigger.new){
        if(!String.isBlank(cs.HID_Form__c)){
            relatedAccountsHIDs.add(cs.HID_Form__c);
            if(!String.isBlank(cs.SuppliedEmail)){
                relatedContactsEmails.add(cs.SuppliedEmail);
            }
        }
    }
    // get related accounts & contacts
    for(Account acc: [Select Id, HID__c from Account where HID__c IN:relatedAccountsHIDs]){
        relatedAccounts.put(acc.HID__c, acc);
    }

    for(Contact con: [Select Id, Email from Contact where  Email IN:relatedContactsEmails ]){
         relatedContacts.put(con.Email, con);
    }

    //set accountid & contactId
      for(Case cs: Trigger.new){
        if(!String.isBlank(cs.HID_Form__c) && relatedAccounts.containsKey(cs.HID_Form__c)){ // a related account exists
            cs.AccountId = relatedAccounts.get(cs.HID_Form__c).Id;

            if(!String.isBlank(cs.SuppliedEmail) && relatedContacts.containsKey(cs.SuppliedEmail)){
                cs.ContactId = relatedContacts.get(cs.SuppliedEmail).Id;
            }else{
                System.debug('Error: no contact');
            }
        }else{ // no related account
            System.debug('Error: do not treat this case further');
        }
    }

}
apex apex-code apex-trigger salesforce-developer
1个回答
0
投票

您需要创建一个用@isTest装饰器注释的类,该装饰器封装了您的测试逻辑。这样的事情应该会让您入门:

@istest
public class CaseBeforeInsert_Test {

    @isTest
    public static void CaseBeforeInsert_HasFormAndSuppliedEmail_AccountAndContactAreSet() {

        Account acct = new Account(Name = 'Some Account', HID__c = 'Avengers');
        insert acct;

        Contact con = new Contact(FirstName = 'Tony', LastName = 'Stark', Email = '[email protected]');
        insert con;

        System.startTest();

        Case c = new Case(HID_Form__c = 'Avengers', SuppliedEmail = '[email protected]');
        insert c;

        System.stopTest();

        Case insertedCase = [SELECT AccountId, ContactId FROM Case WHERE Id = :c.Id];
        System.assertEquals(acct.Id, insertedCase.AccountId);
        System.assertEquals(con.Id, insertedCase.ContactId);
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.