Test Methods

Test methods are static Apex code methods, annotated with @isTest. They are written within an outer class, also annotated with @isTest. Tests are subject to the same governor limits as all Apex code, but every test method is completely independent for the purposes of limit tracking, not cumulative. Also, test classes are not counted against the code size limit for a Force.com organization.

A test is considered successful if its method is executed without encountering an uncaught exception. A common testing pattern is to make a series of assertions about the target code’s state using the built-in method System.assert. The argument of assert is a Boolean expression. If it evaluates to true, the program continues; otherwise, a System.Exception is thrown and causes the test to fail.

Listing 4.41 shows a simple test method. It asserts two statements. The second is false, so the test always fails.

Listing 4.41 Test Method


@isTest static void negativeTest() {
  Integer i = 2 + 2;
  System.assert(i == 4);
  System.assert(i / 2 == 1);
}


Rather than adding two numbers together, most unit tests perform substantial operations in one or more other classes. Sometimes it’s necessary to examine the contents of a private variable or invoke a protected method from a test. Rather than relaxing the access modifiers of the code to make them visible to tests, annotate the code you are testing with @TestVisible. This annotation provides your test code with privileged access but otherwise preserves the access modifiers in your code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.109.34