Testing Your Apex Code
Before you can upload a managed package, you must write and execute tests for your Apex
code to meet minimum code coverage requirements. Also, all tests must run without errors when
you upload your package to AppExchange.
To package your application and components that depend on Apex code, the following must be true.
- Unit tests must cover at least 75% of your Apex code, and all of those tests must
complete successfully.
Note the following.
- When deploying Apex to a production organization, each unit test in your organization namespace is executed by default.
- Calls to System.debug aren’t counted as part of Apex code coverage.
- Test methods and test classes aren’t counted as part of Apex code coverage.
- While only 75% of your Apex code must be covered by tests, don’t focus on the percentage of code that is covered. Instead, make sure that every use case of your application is covered, including positive and negative cases, as well as bulk and single records. This approach ensures that 75% or more of your code is covered by unit tests.
- Every trigger must have some test coverage.
- All classes and triggers must compile successfully.
This sample shows an Apex test class for a custom object that’s wired up to a
component.
@isTest
class TestExpenseController {
static testMethod void test() {
//Create new expense and insert it into the database
Expense__c exp = new Expense__c(name='My New Expense',
amount__c=20, client__c='ABC',
reimbursed__c=false, date__c=null);
ExpenseController.saveExpense(exp);
//Assert the name field and saved expense
System.assertEquals('My New Expense',
ExpenseController.getExpenses()[0].Name,
'Name does not match');
System.assertEquals(exp, ExpenseController.saveExpense(exp));
}
}
For more
information on distributing Apex code, see Debugging, Testing, and Deploying Apex in the
Apex Developer Guide.