Wednesday 3 June 2015

Tips and Tricks For Test Class

Why we  need to write test class ? Some people will answer like we need code coverage to deploy code to production, as we don't have right to write code in production directly  . Yes it is correct but not 100 percent  .Test class  basically helps us to test our functionality of code which is important to develop  a better application . So we should not concentrate only code coverage though it is required  .
We should write proper test case to test all types of scenario . We should not happy with 75 % code coverage ,we should try to achieve 100 % coverage with all test scenario like  positive ,negative and bulk unit test .

Below points we should know as a developer :-

  • Test class must start with @isTest annotation if class class version is more than 25
  • Test environment support @testVisible, @testSetUp as well
  • Unit test is to test particular piece of code working properly or not .
  • Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
  • To deploy to production at least 75% code coverage is required and al test case should pass .
  • System.debug statement are not counted as a part of apex code coverage .
  • Test method and test classes are not counted as a part of code coverage .
  • We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative, bulk and single record .
  • Single Action -To verify that the the single record produces the correct and expected result .
  • Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
  • Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
  • Negetive Testcase :-Not to add future date ,Not to specify negative amount.
  • .Restricted User :-Test whether a user with restricted access used in your code .
  • .Conditional and ternary operator are not considered executed unless both positive and negative branches are executed .
  • Unit test are class methods that verify whether a particular piece of code is error free or not .
  • Test class should be annoted with isTest .
  • isTest annotation with test method  is equivalent to  testMethod keyword .
  • Test method should static and no void return type .
  • Test class and method default access is private ,no matter to add access specifier .
  • Classes with isTest annotation can't be a interface or enum .
  • Test method code can't be invoked by non test request .
  • Stating with salesforce API 28.0 test method can not reside inside non test classes .
  • @Testvisible annotaion to make visible private methods inside test classes.
  • Test method can not be used to test webservice call out .Instaed use call out mock .
  • You cann't  send email fron test method.
  • User,profile,organisation,AsyncApexjob,Corntrigger,RecordType,ApexClass,ApexComponent,ApexPage we can access without (seeAllData=true) .
  • SeeAllData=true will not work for API 23 version eailer .
  • Acessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
  • Create Test Factory class with isTest annotation to exclude from organization code size limit .
  • @testSetup to create test records once in a method  and use in every test method in the test class .
  • We can run unit test for a specific class, set of classes and all classes .
  • We can run unit test by using Salesforce Standard UI, IDE ,Console ,API.
  • Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
  • As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
  • System.runAs will not enforce user permission or field level permission .
  • Every test to runAs count against the total number of DML issued in the process . 

Below code snippet help you to start writing test class :-

Test class definition :-
Sample 1-
private class MyTestClass {}
Sample 2-Grant test classes to  access  all data in the organization.
private class MyTestClass {}
Sample 3: Specify whether test class execute during package installation or not 
private class MyTestClass {}
Test method definition :- Sample 1-with testmethod keyword . static testMethod void testName() { // code_block } Sample 2:-Here we can avoid testMethod with @isTest annotation which will help us to get benifit of parameters indivisually incase not there in class level . @isTest static void testName() { // code_block }

Below tips  helps us to move towards 100 % code coverage :-

1.Tips for standardcontroller

ApexPages.standradController con=ApexPages.StandradController(Needs to pass the instance of the standard/Custom Object);


ApexPages.standradSetController con=ApexPages.StandradSetController(Needs to pass the list of the standard/Custom Object);

3.For wrapper class

ClassName.WrapperclassName wrp=new ClassName.WrapperclassName();

4.Test code catch block .

We need to create a excption in test method to cover .We can do in two different ways one suppose we want an excption on update .we can do like below .

 Trick 1-

Account acc =new Account();
  insert/update acc;
}catch(Exception ex){}
As mandatory fields are missing it will throw exception and it will cover the catch block .
Trick 2-We need to add two line  of code in class like below .
   DML statement;
Integer intTest =20/0;
} catch(Exception ex){
ApexPages.Message msg = new              ApexPages.Message(ApexPages.Severity.error,qe.getMessage());
There is a class named Test in apex which has some method which help us to write some useful test case   Test class method


  1. Introduction of cloud servers have created a greatest impact over data interpretation. Also they made a history in cloud computing. Handling data made much easier and more comfortable like never before. Your content tells the same about the emerging technology. Thanks for sharing this information in here.

    Salesforce training in chennai | Salesforce course in chennai

  2. Cloud servers are the best in safe guarding one's information thorugh online. Without this dedicated methodology many companies would have not existed at all. The same though has been furnished above. Thanks for sharing this worth while content in here. Keep writing article like this.

    Salesforce course in chennai | Salesforce course in chennai | Salesforce administrator training in chennai

  3. A nice article here with some useful tips for those who are not used-to comment that frequently. Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.

    Salesforce Training in Chennai

    AWS Training in Chennai

  4. Whatever we gathered information from the blogs, we should implement that in practically then only we can understand that exact thing clearly, but it’s no need to do it, because you have explained the concepts very well. It was crystal clear, keep sharing..
    Salesforce Training in Chennai
    German Classes in Chennai
    Salesforce Admin Training in Chennai
    Salesforce Training Chennai
    German Training Institute in Chennai
    german language coaching centres in chennai

  5. Thank you for benefiting from time to focus on this kind of, I feel firmly about it and also really like comprehending far more with this particular subject matter. In case doable, when you get know-how, is it possible to thoughts modernizing your site together with far more details? It’s extremely useful to me

    Data Science Training in Chennai
    Data Science training in kalyan nagar
    Data science training in Bangalore
    Data Science training in marathahalli
    Data Science interview questions and answers
    Data science training in bangalore

  6. I read this post two times, I like it so much, please try to keep posting & Let me introduce other material that may be good for our community.

  7. I read this post two times, I like it so much, please try to keep posting & Let me introduce other material that may be good for our community. data science courses

  8. Much thanks for composing such an intriguing article on this point. This has truly made me think and I plan to peruse more
    data scientist training and placement

  9. Great to become visiting your weblog once more, it has been a very long time for me. Pleasantly this article i've been sat tight for such a long time. I will require this post to add up to my task in the school, and it has identical subject along with your review. Much appreciated, great offer. data science course in nagpur

  10. I've been looking for info on this topic for a while. I'm happy this one is so great. Keep up the excellent work data science course in surat

  11. Cool you write, the information is very good and interesting, I'll give you a link to my site. data science training in mysore

  12. Гадание какой мужчина - это простейший вариант узнать судьбу с употреблением каких-либо объектов и приемов. Мистические силы и всякие условности хиромантии наукой не установлены, при том многие люди верят в это. Специфический список воздействий, ориентированных на предсказание будущего, именуют ворожба.

  13. I was curious if you ever thought of changing the layout of your site? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having 1 or 2 pictures. Maybe you could space it out better?|