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



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

这是我的代码:

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(( 中调用 insert 语句可确保触发器逻辑在评估断言之前完成。

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

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

最新更新