Unit Test Classes in Apex

Testing is the major thing of the development. In salesforce, Apex Code requires the creation and execution of unit tests. Unit tests are class methods that verify whether a particular piece of code is working properly or not. Unit tests are written in Apex Code and annotated with the “testMethod” keyword.

Important thing to note down before to write TestClass:
– At least 75% of code coverage is required to move the apex code to production from sandboxes.
– Whatever we created the data in test class that won’t save in database. (delete all the data once transaction is done)
– Do not write any SOQLs in test class.
– Do not use “seeAllData=true”, Create own data in test class.
– Use As much as Assertions like “System.AssertEquals” or “System.AssertNotEquals”
– To reset the Governor limits for the particular transcation use system.startTest() and system.stopTest()

Writing a simple Unit Test Class:

Apex Class:
public class NewAccountCreation {
public Account account{get;set;}
public void save(){
Account acc = new Account();
// User enter values in vf page and we are capturing and creating account
acc.name = account.Name;
acc.adress = account.adress;
Insert acc;
}
}

// Unit Test class for above apex Class
@isTest
private class NewAccountCreationTest{
public static testMethod void NewAccountCreationTestMethod(){
NewAccountCreation accountCreation = new NewAccountCreation ();
Account acc = new Account();
acc.name = ‘NewAccount’;
acc.address = ‘bangalore’;
insert acc;
accountCreation.save();
}
}