• No results found

Adding a Test Class

In document Salesforce Apex (Page 34-37)

The first line of code defines the trigger:

trigger HelloWorldTrigger on Book__c (before insert) {

It gives the trigger a name, specifies the object on which it operates, and defines the events that cause it to fire. For example, this trigger is called HelloWorldTrigger, it operates on the Book__c object, and runs before new books are inserted into the database.

The next line in the trigger creates a list of book records named books and assigns it the contents of a trigger context variable called Trigger.new. Trigger context variables such as Trigger.new are implicitly defined in all triggers and provide access to the records that caused the trigger to fire. In this case, Trigger.new contains all the new books that are about to be inserted.

Book__c[] books = Trigger.new;

The next line in the code calls the method applyDiscount in the MyHelloWorld class. It passes in the array of new books.

MyHelloWorld.applyDiscount(books);

You now have all the code that is needed to update the price of all books that get inserted. However, there is still one piece of the puzzle missing. Unit tests are an important part of writing code and are required. In the next step, you will see why this is so and you will be able to add a test class.

See Also:

Writing Your First Apex Class and Trigger Adding an Apex Class

Adding a Test Class

Adding a Test Class

Prerequisites:

A Salesforce account in a sandbox Unlimited or Enterprise Edition organization, or an account in a Developer organization.

• The HelloWorldTrigger Apex trigger.

In this step, you add a test class with one test method. You also run the test and verify code coverage. The test method exercises and validates the code in the trigger and class. Also, it enables you to reach 100% code coverage for the trigger and class.

Note: Testing is an important part of the development process. Before you can deploy Apex or package it for the Force.com AppExchange, the following must be true.

• At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully.

Note the following.

◊ When deploying to a production organization, every unit test in your organization namespace is executed.

◊ Calls to System.debug are not counted as part of Apex code coverage.

◊ Test methods and test classes are not counted as part of Apex code coverage.

◊ While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of code that is covered. Instead, you should make sure that every use case of your application is covered, including positive and negative cases, as well as bulk and single record. This should lead to 75% or more of your code being covered by unit tests.

• Every trigger must have some test coverage.

• All classes and triggers must compile successfully.

1. From Setup, click Develop > Apex Classes and click New.

2. In the class editor, add this test class definition, and then click Save.

@isTest

private class HelloWorldTestClass {

static testMethod void validateHelloWorld() {

Book__c b = new Book__c(Name='Behind the Cloud', Price__c=100);

System.debug('Price before inserting new book: ' + b.Price__c);

// Insert book insert b;

// Retrieve the new book

b = [SELECT Price__c FROM Book__c WHERE Id =:b.Id];

System.debug('Price after trigger fired: ' + b.Price__c);

// Test that the trigger correctly updated the price System.assertEquals(90, b.Price__c);

} }

This class is defined using the @isTest annotation. Classes defined as such can only contain test methods. One advantage to creating a separate class for testing as opposed to adding test methods to an existing class is that classes defined with isTest don't count against your organization limit of 3 MB for all Apex code. You can also add the @isTest annotation to individual methods. For more information, see IsTest Annotation on page 154 and Understanding Execution Governors and Limits on page 258.

The method validateHelloWorld is defined as a testMethod. This means that if any changes are made to the database, they are automatically rolled back when execution completes and you don't have to delete any test data created in the test method.

First the test method creates a new book and inserts it into the database temporarily. The System.debug statement writes the value of the price in the debug log.

Book__c b = new Book__c(Name='Behind the Cloud', Price__c=100);

System.debug('Price before inserting new book: ' + b.Price__c);

// Insert book insert b;

Once the book is inserted, the code retrieves the newly inserted book, using the ID that was initially assigned to the book when it was inserted, and then logs the new price, that the trigger modified:

// Retrieve the new book

b = [SELECT Price__c FROM Book__c WHERE Id =:b.Id];

System.debug('Price after trigger fired: ' + b.Price__c);

When the MyHelloWorld class runs, it updates the Price__c field and reduces its value by 10%. The following line is the actual test, verifying that the method applyDiscount actually ran and produced the expected result:

// Test that the trigger correctly updated the price System.assertEquals(90, b.Price__c);

3. Click Run Test in the class page to run all the test methods in this class. In this case, we have only one test method.

The Apex Test Result page appears after the test finishes execution. It contains the test result details such as the number of test failures, code coverage information, and a link to a downloadable log file.

4. Click Download and select to open the log file. You can find logging information about the trigger event, the call to the applyDiscount class method, and the debug output of the price before and after the trigger.

Alternatively, you can use the Developer Console for debugging Apex code. See “Developer Console” in the Salesforce online help.

5. You can also run the test through the Apex Test Execution page, which runs the test asynchronously, which means that you don't have to wait for the test run to finish to get the test result, but you can perform other tasks in the user interface while the test is still running and then visit this page later to check the test status.

a. From Setup, click Develop > Apex Test Execution.

b. Click Run Tests.

c. Select the class HelloWorldTestClass, and then click Run.

After a test finishes running, you can:

• Click the test to see result details; if a test fails, the first error message and the stack trace display.

Click View to see the source Apex code.

6. After the test execution completes, verify the amount of code coverage.

a. From Setup, click Develop > Apex Classes.

b. Click Calculate your organization's code coverage to see the amount of code in your organization that is covered by unit tests.

c. In the Code Coverage column, click 100% to see the lines of code covered by unit tests.

Take a look at the list of triggers from Setup by clicking Develop > Apex Triggers. You'll see that the trigger you wrote also has 100% of its code covered.

By now, you completed all the steps necessary for having some Apex code that has been tested and that runs in your development environment. In the real world, after you’ve sufficiently tested your code and you’re satisfied with it, you want to deploy the

code along with any other prerequisite components to a production organization. The next step will show you how to do this for the code and custom object you’ve just created.

See Also:

Writing Your First Apex Class and Trigger Adding an Apex Trigger

In document Salesforce Apex (Page 34-37)