【问题标题】:whats is happening in this apex code?这个顶点代码发生了什么?
【发布时间】:2017-05-19 07:14:35
【问题描述】:
String color1 = moreColors.get(0);
String color2 = moreColors[0];
System.assertEquals(color1, color2);

// Iterate over a list to read elements
for(Integer i=0;i<colors.size();i++) {
    // Write value to the debug log
    System.debug(colors[i]);
}

我正在学习 Apex,刚刚开始 System.assertEquals(color1, color2); 行的含义是什么,这里的调试日志是什么意思?

【问题讨论】:

  • 在我看来这就像一个 JUnit 断言语句 - 用于单元测试。

标签: salesforce apex


【解决方案1】:

System.assert、System.assertEquals、System.assertNotEquals。我认为这是 Apex 中最重要的三个方法调用。

这些是断言语句。它们用于测试以验证您拥有的数据是否符合您的期望。

System.assert 测试一个逻辑语句。如果该语句的计算结果为 True,则代码将继续运行。如果该语句的计算结果为 False,则代码将引发异常。

System.assertEquals 测试两个值是否相等。如果两者相等,则代码继续运行。如果它们不相等,则代码将引发异常。

System.assertNotEqual 测试两个值不相等。如果两者不相等,则代码继续运行。如果相等,则代码抛出异常。

这些对于完成系统测试至关重要。在 Apex Code 中,您必须有 75% 的线路测试覆盖率。许多人通过生成仅覆盖 75% 的代码行的测试代码来做到这一点。然而,这是一个不完整的测试。一个好的测试类实际上会测试代码是否符合您的期望。这对于确保您的代码实际工作非常有用。这使得调试和回归测试变得更加容易。例如。让我们创建一个名为 square(Integer i) 的方法,对返回的整数求平方。

public static Integer square( Integer i ) {
    return i * i;
}

一个糟糕的测试方法就是:

@isTest
public static void test_squar() {
    square( 1 );
}

一个好的测试方法可能是:

@isTest
public static void test_square() {
    Integer i;
    Integer ret_square;

    i = 3;
    ret_square = square( i );
    System.assertEquals( i * i; ret_square );
}

我可能会这样写:

@isTest
public static void test_square() {
    for( Integer i = 0; i < MAX_TEST_RUNS; i++ ) {
        System.assertEquals( i*i, square( i ) );
    }
}

良好的测试实践对于成为一名优秀的开发人员来说是不可或缺的。查看更多关于测试驱动的开发。 https://en.wikipedia.org/wiki/Test-driven_development

【讨论】:

    【解决方案2】:

    一行一行...

    //Get color in position 0 of moreColors list using the list get method store in string color1
    String color1 = moreColors.get(0); 
    
    //Get color in position 0 of moreColors list using array notation store in string color2, 
    //basically getting the same value in a different way
    String color2 = moreColors[0]; 
    
    //Assert that the values are the same, throws exception if false
    System.assertEquals(color1, color2);
    
    // Iterate over a list to read elements
    for(Integer i=0;i<colors.size();i++) {
        // Write value to the debug log
        System.debug(colors[i]);//Writes the value of color list ith position to the debug log
    }
    

    如果您通过开发者控制台匿名运行此代码,您可以查找以 DEBUG| 为前缀的行查找语句,例如

    16:09:32:001 USER_DEBUG 1|DEBUG|蓝色

    有关系统方法的更多信息,请访问https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_system.htm#apex_System_System_methods

    【讨论】:

      猜你喜欢
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 2018-07-28
      相关资源
      最近更新 更多