salesforce - Salesforce 中的触发器测试类
问题描述
解决方案
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>
推荐阅读
- react-native - 如何在 React Native 中停止不必要的重新渲染组件
- docker - 如何使用 docker 安装 symfony 项目?
- c# - 从另一个线程追加 RichTextBox
- java - 每当我在 SpringBoot 应用程序中调用服务时,从文件中运行 sql 和 plsql 查询
- toloka - 字符串数组作为输入
- c++ - QGroundControl 在 Mac 上使用 Qt 构建
- elf - Uboot bootloader linux镜像启动问题
- wcf - 绑定属性消息在此上下文中不支持值 mtom
- apache-kafka - 使用log4j2将日志附加到kafka时如何限制kafka打印速率?
- android-studio - MediaPlayer.Pause() 方法不暂停音频