testing - 我如何使用断言方法为顶点触发器编写测试?

标签 testing triggers apex

如何使用 assert 方法为 apex 触发器编写测试?

这是我的代码:

trigger ProductTrigger on Product__c (before insert, before update) { 
    Schema.DescribeFieldResult F = Product__c.Description__c.getDescribe(); 
    Integer lengthOfField = F.getLength();
    List<Product__c> prList = new list<Product__c>(); 
    for(Product__c pr: trigger.new){
        pr.AddedDate__c=system.today();
        if (String.isNotEmpty(pr.Description__c)) {
           pr.Description__c = pr.Description__c.abbreviate(lengthOfField);
        }
    } 
}

最佳答案

您可以像测试普通逻辑类一样测试触发器。只需创建一个新的测试类,然后在您的测试类中创建一个新产品,插入它,查询它,并验证您希望触发器更改的字段是否已更新。

在 StartTest()/StopTest() 中调用插入语句确保触发逻辑在评估断言之前完成。

您可以以相同的方式测试更新逻辑,还可以测试插入和更新对象列表。

@isTest
public class Test_ProductTrigger {

    @isTest
    static void test_getNewApp()
    {
        Product__c product = Product__c();
        product.yourFieldToTest = 'someValue';

        Test.startTest();
             insert products;
        Test.stopTest();

        Product__c newProduct = [SELECT yourFieldToTest FROM Product WHERE Id = product.Id LIMIT 1];

        system.assert('yourExpectedValue' == newProduct.yourFieldToTest);
        // You can also use system.assertEquals to do the same test
        system.assertEquals('yourExpectedValue', newProduct.yourFieldToTest);

    }
}

关于testing - 我如何使用断言方法为顶点触发器编写测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56723802/

相关文章:

error-handling - apex addError-删除默认错误消息

java - 为什么 Apex 在这个集合上向后迭代?

检查客户端证书的 HTTPS 测试服务器

ruby - 如何调用参数传递的名称的方法?

mysql - 基于If条件在Mysql触发器中使用Select INTO语句

wpf - 使用 StyleTriggers 自动隐藏进度条

r - 如何从 R 调用 Rscript?

python - 如何确保被测函数是唯一被调用的函数?

MySQL Trigger Insert After with Select 来自不同表的查询

salesforce - 无法在开发者控制台中使用 "Query Editor"