Wednesday, 5 June 2013

Test Methods: What, Why and How?

I was thinking to write something from a long time and I came up with this today(Finally I am active again on blogger :)).
I am big fan of Salesforce developer community and I daily visit it. Not because of I am expert and can answer all the queries there, but It helps me a lot to increase my knowledge. I learn something new daily from there and implement it in real life(how easy it is).

After seeing various post on community, I realized that some people are not sure about the test methods. Each day I do see 2-3 posts like, how to increase coverage, help in writing test methods, assertion failed and many more. and this encouraged me to write this post.

Let me start now without wasting your time :P.

  1. What is test method?
    [Answer]: I hope you all know, but still I would like to share :). Test method is a way to test your functionality from developer perspective. Each time when you deploy your changes to new org, you really can't test everything from UI as it will be time consuming, so test methods are the way to test if everything is working fine without user interface.
  2. Why we write test method?
    [Answer]: Suppose you implemented a functionality today and it was successfully deployed. You have test method with all the use cases covered . A month later, new enhancement comes and you implement it. Now you can run your test method to see the impact on existing functionality. 
  3. How to write test methods?
    [Answer]: I hope you all already know answer of this, but today I would like to explain this very simple way with a simple program.
Suppose I have a method, which takes marks of Science and Maths subject and returns total.

My method would be something like this:

public class MyController {
 //This method takes science and Maths marks and return total of these
 public Integer sum(Integer m1, Integer m2) {
  //return sum of these 2
  return m1 + m2;

Now you can see here is, if I pass 50 and 60 in method, results would be 50+60=110.
That is what QA people will be testing from UI.

but we are developer and do everything with code :). 

so as I said, if I pass 50 and 60 in sum method, it should return 50+60=110.

Let's start writing test method

@isTest : This anotation defines that your class is a test class

private class Test_MyController {

 //test sum method
 static testMethod void testSUM() {
  //Instantiate controller class
  MyController controller = new MyController();

  //Call Sum method
  Integer sum = controller.sum(50, 60);

  //Expected results is 110 and actual should also be 110
  //Check result
  System.assertEquals(110, sum);

and that's all :). Isn't it cool? 

Now anytime you make changes in your controller's SUM method, you can always run the test method to check if there is any impact on existing functionality. Also make sure to keep you test method updated as per the new changes :).