Thursday, 30 August 2012

Adding a Test for the Batch Apex Class


Prerequisites:
  • Tutorial #1: Creating Warehouse Custom Objects
  • Tutorial #8: sObjects and the Database
  • Tutorial #12: Apex Unit Tests
In this lesson, you’ll add a test class for the CleanUpRecords batch class. The test in this class invokes the batch job and verifies that it deletes all merchandise records that haven’t been purchased.
  1. In the Repository tab, click Classes in the Setup Entity Type section, and then click New.
  2. For the class name, enter TestCleanUpBatchClass and click OK.
  3. Delete the auto-generated code and add the following.
    @isTest
    private class TestCleanUpBatchClass {
    
        static testmethod void test() {
            // The query used by the batch job. 
        
            String query = 'SELECT Id,CreatedDate FROM Merchandise__c ' + 
                       'WHERE Id NOT IN (SELECT Merchandise__c FROM Line_Item__c)';
    
           // Create some test merchandise items to be deleted 
        
           //   by the batch job. 
        
           Merchandise__c[] ml = new List<Merchandise__c>();
           for (Integer i=0;i<10;i++) {
               Merchandise__c m = new Merchandise__c(
                   Name='Merchandise ' + i,
                   Description__c='Some description',
                   Price__c=2,
                   Total_Inventory__c=100);
               ml.add(m);
           }
           insert ml;
    
           Test.startTest();
           CleanUpRecords c = new CleanUpRecords(query);
           Database.executeBatch(c);
           Test.stopTest();
    
           // Verify merchandise items got deleted  
        
           Integer i = [SELECT COUNT() FROM Merchandise__c];
           System.assertEquals(i, 0);
        }
    }
  4. Click Save.

Tell Me More...

  • The test class contains one test method called test. This test method starts by constructing the query string that is to be passed to the constructor of CleanUpRecords. Since a merchandise item that hasn’t been purchased is a merchandise item that doesn’t have line items associated with it, the SOQL query specifies the following:.
    WHERE Id NOT IN (SELECT Merchandise__c FROM Line_Item__c)
    The subquery
    SELECT Merchandise__c FROM Line_Item__c
    gets the set of all merchandise items that are referenced in line items. Since the query uses the NOT IN operator in the WHERE clause, this means the merchandise items that aren’t referenced in line items are returned.
  • The test method inserts 10 merchandise items with no associated line items to be cleaned up by the batch class method. Note that the number of records inserted is less than the batch size of 200 because test methods can execute only one batch total.
  • Next, the batch class is instantiated with the query with this statement where the query variable is passed to the constructor ofCleanUpRecords.:
    CleanUpRecords c = new CleanUpRecords(query);
  • The batch class is invoked by calling Database.executeBatch and passing it the instance of the batch class:
    Database.executeBatch(c);
  • The call to Database.executeBatch is included within the Test.startTest and Test.stopTest block. This is necessary for the batch job to run in a test method. The job executes after the call to Test.stopTestAny asynchronous code included withinTest.startTest and Test.stopTest gets executed synchronously after Test.stopTest.
  • Finally, the test verifies that all test merchandise items created in this test got deleted by checking that the count of merchandise items is zero.
  • Even though the batch class finish method sends a status email message, the email isn’t sent in this case because email messages don’t get sent from test methods.

52 comments:

  1. Thanks admin, for sharing your valuable post about cloud computing. This technology ensure maximum advantage to the small business organization.
    cloud training in Chennai

    ReplyDelete
  2. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing. Cloud Computing Training in chennai | Cloud Computing Training chennai | Cloud Computing Course in chennai | Cloud Computing Course chennai

    ReplyDelete
  3. Cloud is one of the tremendous technology that any company in this world would rely on(cloud computing training chennai). Using this technology many tough tasks can be accomplished easily in no time. Your content are also explaining the same(Cloud computing training centers in chennai). Thanks for sharing this in here. You are running a great blog, keep up this good work.

    ReplyDelete
  4. Data are the main part in creating a company's revenue. Managing those data is highly chanllengable in this least secured world. But there are veterans whom we can trust to safeguard our data. Thanks for sharing this wonderful information in here. It helped me a lot.

    Salesforce course in chennai | Salesforce developer training in chennai

    ReplyDelete
  5. Really Good blog post.provided a helpful information.I hope that you will post more updates like this salesforce Online Training Bangalore

    ReplyDelete
  6. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.

    Hadoop training in chennai

    ReplyDelete
  7. Your new valuable key points simply much a person like me and extremely more to my office workers. With thanks; from every one of us.
    Best Python training Institute in chennai

    ReplyDelete
  8. Nice tips. Very innovative... Your post shows all your effort and great experience towards your work Your Information is Great if mastered very well.

    python training in omr

    python training in annanagar | python training in chennai

    python training in marathahalli | python training in btm layout

    python training in rajaji nagar | python training in jayanagar

    ReplyDelete
  9. Well done! Pleasant post! This truly helps me to discover the solutions for my inquiry. Trusting, that you will keep posting articles having heaps of valuable data. You're the best! 
    Hadoop Training in Chennai
    Hadoop Training in Bangalore
    Big data training in tambaram
    Big data training in Sholinganallur
    Big data training in annanagar

    ReplyDelete
  10. This is a good post. This post give truly quality information. I’m definitely going to look into it. Really very useful tips are provided here. thank you so much. Keep up the good works.
    MEAN stack training in annanagar
    MEAN stack training in Velachery
    MEAN stack training Sholinganallur

    ReplyDelete
  11. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
    Devops training in velachery
    Devops training in annanagar
    DevOps online Training

    Devops Training in Chennai

    Devops Training in Bangalore

    ReplyDelete
  12. I really like the dear information you offer in your articles. I’m able to bookmark your site and show the kids check out up here generally. Im fairly positive theyre likely to be informed a great deal of new stuff here than anyone
    python training in tambaram
    python training in annanagar
    python training in OMR

    ReplyDelete
  13. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
    java training in chennai | java training in bangalore

    java online training | java training in pune

    ReplyDelete
  14. I am sure this post has helped me save many hours of browsing other related posts just to find what I was looking for. Many thanks!
    python training in velachery
    python training institute in chennai

    ReplyDelete
  15. Were a gaggle of volunteers as well as starting off a brand new gumption within a community. Your blog furnished us precious details to be effective on. You've got completed any amazing work!
    angularjs Training in chennai
    angularjs Training in chennai

    angularjs-Training in tambaram

    angularjs-Training in sholinganallur

    angularjs-Training in velachery

    ReplyDelete
  16. This comment has been removed by the author.

    ReplyDelete

  17. Howdy, would you mind letting me know which web host you’re utilizing? I’ve loaded your blog in 3 completely different web browsers, and I must say this blog loads a lot quicker than most. Can you suggest a good internet hosting provider at a reasonable price?
    Amazon Web Services Training in OMR , Chennai | Best AWS Training in OMR,Chennai
    Amazon Web Services Training in Tambaram, Chennai|Best AWS Training in Tambaram, Chennai

    ReplyDelete
  18. I am really enjoying reading your well written articles.
    It looks like you spend a lot of effort and time on your blog.
    I have bookmarked it and I am looking forward to reading new articles. Keep up the good work..
    Franchise For Spoken English Classes
    Computer Training Institute Franchise
    English Language School Franchise
    Best Education Franchise In India
    Franchise For Spoken English Classe
    Training Franchise Opportunities In India

    ReplyDelete
  19. thank you for sharing such a nice and interesting blog with us. i have seen that all will say the same thing repeatedly. But in your blog, I had a chance to get some useful and unique information. I would like to suggest your blog in my dude circle. please keep on updates. hope it might be much useful for us. keep on updating...
    Java Training in Chennai
    Java course in Chennai
    Java Training Institute in Chennai
    Best Java Training Institute in Chennai
    Java Training

    ReplyDelete
  20. I’m surprised at how fast your blog loaded on my cell phone. I’m not even using WIFI, just 3G. Anyways, awesome blog!
    safety course in chennai

    ReplyDelete
  21. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.

    Oracle Training in Chennai | Best Oracle Training Institute in Chennai
    Web Design Training in Chennai
    Web Design Training in Chennai|Best Web Design Training in Chennai
    AngularJS Training in Chennai |Advanced SAS Training in Chennai | Best SAS Training in Chennai

    ReplyDelete
  22. Superb. I really enjoyed very much with this article here. Really it is an amazing article I had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article.thank you for sharing such a great blog with us.
    best institute for big data in chennai
    big data classes in chennai
    Hadoop Admin Training in Chennai
    CCNA Training in Chennai
    CCNA course in Chennai
    CCNA Training institute in Chennai

    ReplyDelete
  23. Really great post, Thank you for sharing This knowledge.Excellently written article, if only all bloggers offered the same level of content as you, the internet would be a much better place. Please keep it up!
    python Training in Pune
    python Training in Chennai
    python Training in Bangalore

    ReplyDelete
  24. I really appreciate this post. I’ve been looking all over for this! Thank goodness I found it on Bing. You’ve made my day! Thx again!

    Microsoft Azure online training
    Selenium online training
    Java online training
    Java Script online training
    Share Point online training


    ReplyDelete
  25. Are you interested in doing Data Science Training in Chennai with a Certification Exam? Catch the best features of Data Science training courses with Infycle Technologies, the best Data Science Training & Placement institutes in and around Chennai. Infycle offers the best hands-on training to the students with the revised curriculum to enhance their knowledge. In addition to the Certification & Training, Infycle offers placement classes for personality tests, interview preparation, and mock interviews for clearing the interviews with the best records. To have all it in your hands, dial 7504633633 for a free demo from the experts.

    ReplyDelete
  26. OctaFx Review has been proven to be an extremely valuable investment tool. Traders can identify trading opportunities using action of market participants through charts, patterns and indicators.

    ReplyDelete
  27. As you add a test for the Batch Apex Class, ensure your coding journey aligns with a healthy smile. Explore Delhi Dentists to balance technical precision with oral well-being. Just like error-free code, a perfect smile is key to a seamless experience in your coding endeavors.

    ReplyDelete