这个顶点代码中发生了什么?

whats is happening in this apex code?

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); 行的含义以及这里的调试日志是什么意思?

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

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

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

System.assertEquals 测试两个值是否相等。如果两者相等,则代码保持运行。如果它们不相等,代码将抛出异常。

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

这些对于完成系统测试至关重要。在 Apex 代码中,您必须具有 75% 的线路测试覆盖率。许多人通过生成仅覆盖其代码行 75% 的测试代码来做到这一点。然而,这是一个不完整的测试。一个好的测试 class 实际测试代码是否按照您的预期进行。这对于确保您的代码实际工作非常有用。这使得调试和回归测试更加容易。例如。让我们创建一个名为 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

逐行...

//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| blue

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