How can i increase my code coverage in test class?? I am new to salesforce i am now trying to write some test classes please any one help me out by telling few tips/steps to increase code coverage
-
welcome to salesforce.stackoverflow user4986(tip: create a meaningful username). Just some stips/steps is a very broad question to which a lot of resources and answers already exist online. You could help us help you by explaining what you've already mastered, and which specific area is giving you a challenge to understand or implement.– Samuel De RyckeCommented Mar 3, 2014 at 10:03
2 Answers
As with any other platform/language, the goal is to write tests that cover all the use cases of your code (not just the maximum number of lines).
Below is an example of testing a trigger (taken from a developerforce article and modified slightly by me)
Trigger
trigger OverwriteTestAccountDescriptions on Account (before insert) {
for(Account a: Trigger.new){
if (a.Name.toLowerCase().contains('test')){
a.Description = 'This is an account description.';
}
}
}
Test Method
static testMethod void verifyAccountDescriptionsWhereOverwritten(){
// Perform our data preparation.
List<Account> accounts = new List<Account>{};
for(Integer i = 0; i < 200; i++){
Account a = new Account(Name = 'Test Account ' + i);
accounts.add(a);
}
// Start the test, this changes governor limit context to
// that of trigger rather than test.
test.startTest();
// Insert the Account records that cause the trigger to execute.
insert accounts;
// Stop the test, this changes limit context back to test from trigger.
test.stopTest();
// Query the database for the newly inserted records.
List<Account> insertedAccounts = [SELECT Name, Description
FROM Account
WHERE Id IN :accounts];
// Assert that the Description fields contains the proper value now.
for(Account a : insertedAccounts){
System.assertEquals(
'This is an account description.',
a.Description);
}
}
You should also note that in newer version of the API you must put test in a separate class to the code being tested. The latest information about apex testing can always be found in the Apex Code Developer's Guide.
In fact code coverage is just parameter, the most important thing is how you test logic. Assertions test how logic works, code coverage just show us if this part of code was run during test.
Check this:
http://wiki.developerforce.com/page/How_to_Write_Good_Unit_Tests
It good idea to start reading before you ask so general question. If you need help with some code - please provide us with this code and I am sure someone will help you. But such question as you asked is too general and probably should be closed.