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

    1. The development of artificial intelligence (AI) has propelled more programming architects, information scientists, and different experts to investigate the plausibility of a vocation in machine learning. Notwithstanding, a few newcomers will in general spotlight a lot on hypothesis and insufficient on commonsense application. machine learning projects for final year In case you will succeed, you have to begin building machine learning projects in the near future.

      Projects assist you with improving your applied ML skills rapidly while allowing you to investigate an intriguing point. Furthermore, you can include projects into your portfolio, making it simpler to get a vocation, discover cool profession openings, and Final Year Project Centers in Chennai even arrange a more significant compensation.

      Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account.

      The Nodejs Projects Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

  2. Data processing is the biggest challenge to veterans since last decade. With the invention of cloud solution the burden about data handling become zero percent(Cloud computing training in chennai). Thanks for providing such an useful content here. The information is explicit and clear. Keep blogging like this.(Cloud training in chennai)

  3. 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

  4. 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

  5. Really it was an awesome article...very interesting to read..You have provided an nice article....Thanks for sharing..
    Android Training in Chennai
    Ios Training in Chennai

  6. Training ⁞ CRM Training in Noida ⁞ Salesforce Admin Developer Training in Delhi - ONLINE
    Are you looking for Best Cloud Computing training in Delhi. DIAC offering best online Salesforce training , CRM training, Salesforce Lightning - Admin developer training. Free Demo Class. Call now 9310096831.

  7. 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

  8. Very nice article here you had posted. Thank you for this one and please keep update like this.

    Console Game Testing

    Game Testing Company

    Video Game QA

  9. 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

  10. This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.
    Thank you for this blog. This for very interesting and useful.
    Java training in Chennai
    Java training in Bangalore
    Java online training
    Java training in Pune
    Java training in Bangalore|best Java training in Bangalore

  11. Thank you for the nice article here. Really nice and keep update to explore more gaming tips and ideas.

    Game QA Company

    Game Functionality Testing

    Game Compatibility Testing

    Game Compliance Testing

  12. Nice blog,I understood the topic very clearly,And want to study more like this.
    Data Scientist Course

  13. This is an awesome post.Really very informative and creative contents about Java. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

  14. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.

    data science course

  15. The information which you have provided is very good. It is very useful who is looking for game testing services

  16. I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page!

    Simple Linear Regression

    Correlation vs Covariance

  17. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
    Correlation vs Covariance
    Simple linear regression
    data science interview questions

  18. 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.

  19. 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

  20. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.

    Simple Linear Regression

    Correlation vs Covariance

  21. Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging.After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts likethis.

  22. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.

    data science interview questions

  23. The article unambiguously showed each of the positive and negative sides of the issue. This is indeed a thought infuriating article.
    Data Science training in Mumbai
    Data Science course in Mumbai
    SAP training in Mumbai

  24. Indeed a great article! I am definitely going to bookmark it to go through it over again after work. It seems to cover the major information about the topic in points.
    SAP training in Kolkata
    SAP course in kolkata

  25. While reading this wonderful article, I came across many aspects on which I coincide with you. It made my head bound to ponder over the topic and read it over again.
    SAP training in Mumbai
    SAP course in Mumbai

  26. Highly appreciable regarding the uniqueness of the content. This perhaps makes the readers feels excited to get stick to the subject. Certainly, the learners would thank the blogger to come up with the innovative content which keeps the readers to be up to date to stand by the competition. Once again nice blog keep it up and keep sharing the content as always.
    Data Science Training

  27. Thanks for posting the best information and the blog is very science interview questions and answers

  28. Wonderful blog found to be very impressive to come across such an awesome blog. I should really appreciate the blogger for the efforts they have put in to develop such an amazing content for all the curious readers who are very keen of being updated across every corner. Ultimately, this is an awesome experience for the readers. Anyways, thanks a lot and keep sharing the content in future too.

    data science institute in bangalore

  29. 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

  30. Excellent goods from you about Game Testing Services, man. I’ve understand your stuff previous to and you’re just too excellent on Game Testing Companies. I actually like what you’ve acquired here, certainly like what you are stating and the way in which you say it. You make it enjoyable and you still take care of to keep it sensible content about Game Testing Services USA. I can not wait to read far more Offshore Game Testing Services from you. This is actually a tremendous site..

  31. I am really enjoying reading your well-written articles. It’s hard to come by well-informed people in this particular topic.

    AWS Training in Hyderabad

  32. I was just examining through the web looking for certain information and ran over your blog.It shows how well you understand this subject. Bookmarked this page, will return for extra. data science course in vadodara

  33. Thanks for posting the best information and the blog is very marketing institute in hyderabad

  34. Extremely overall quite fascinating post. I was searching for this sort of data and delighted in perusing this one. Continue posting. A debt of gratitude is in order for sharing. data scientist course in delhi

  35. Stupendous blog huge applause to the blogger and hoping you to come up with such an extraordinary content in future. Surely, this post will inspire many aspirants who are very keen in gaining the knowledge. Expecting many more contents with lot more curiosity further.

    Data Science Certification in Bhilai

  36. Extraordinary blog went amazed with the content that they have developed in a very descriptive manner. This type of content surely ensures the participants to explore themselves. Hope you deliver the same near the future as well. Gratitude to the blogger for the efforts.

    Data Science Training

  37. 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

  38. Thanks for bringing such innovative content which truly attracts the readers towards you. Certainly, your blog competes with your co-bloggers to come up with the newly updated info. Finally, kudos to you.

    Data Science Course in Varanasi

  39. Thanks for posting the best information and the blog is very good.artificial intelligence course in hyderabad

  40. Thanks for posting the best information and the blog is very science institutes in hyderabad

  41. 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

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

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

  44. Thanks for posting the best information and the blog is very science course in ranchi

  45. Thanks for posting the best information and the blog is very analytics course in rajkot

  46. Thanks for posting the best information and the blog is very science course in udaipur

  47. Thanks for posting the best information and the blog is very science training in ranchi

  48. Thanks for posting the best information and the blog is very analytics course in rajkot

  49. Thanks for posting the best information and the blog is very analytics course in ranchi

  50. 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?|