@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 this way should only contain test methods and any methods required to support those test methods. One advantage to creating a separate class for testing is that classes defined with isTest don’t count against your org’s limit of 6 MB of Apex code. You can also add the @isTest annotation to individual methods. For more information, see isTest Annotation and Execution Governors and Limits.
The method validateHelloWorld is defined as a testMethod. This annotation means that if changes are made to the database, they are rolled back when execution completes. You don’t have to delete any test data created in the test method.
First, the test method creates a 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;
After 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. The System.debug statement 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 test verifies that the method applyDiscount ran and produced the expected result.
// Test that the trigger correctly updated the price
System.assertEquals(90, b.Price__c);