Friday, December 9, 2016

How to Write Tests in AEM

Use Case: Writing tests for AEM application.

Current Issue: As your project and code base grows, it is really important to make sure that test coverage for code is there to maintain consistency and sanity of your code. Writing test cases for AEM is little bit different than writing conventional Java test cases, This makes it difficult for beginner to write test cases for AEM application.

Idea of this post to give different options available for writing unit test for AEM services.

Prerequisite:
Good to know:
I would explain how you can have better test coverage for your application by giving different use cases,

Dependencies: It is recommended to have following dependencies in to your pom before start writing for tests for your application
Case 1: Writing test cases for Generic Helper class.

This is simplest use case where your generic helper class (For example StringUtils, DateUtils) is not using any AEM libraries. For this you can simply use Junit to write your unit test. https://www.tutorialspoint.com/junit

Here is very simple example:


Case 2: Writing test cases for AEM Helper class

This is second use case where you want to test AEM helper methods. For this you can use combination of Junit and Mockito. Use Mockito to Mock AEM services and methods and Junit for assertion.

Here is simple example

Case 3: Writing test cases for AEM services

Now it gets little bit tricky where you need to mock certain behavior of bundle and implicit object. That's why Sling has created Mock version of sling objects and wcm.io has created mock version of AEM objects. You can just use aem mock http://wcm.io/testing/aem-mock/ to achieve most of your use cases. (AEM mock extend Sling mock).

here are some of the common use cases you will come across while testing your service.

1) How can I mock content my service is running against ?

For this it is recommended to use contentLoader API http://wcm.io/testing/aem-mock/usage.html to either load existing json based resource (You can simply get it by creating resource in CRXDE and then using something like RESOURCEPATH.infinity.json to get json for that resource) or just create mock resource using ContentBuilder context.create().resource() or ResourceBuilder context.build().resource() http://wcm.io/testing/aem-mock/apidocs/

Note that if you are mocking Page object then you have to use aem mock using aemcontext.pageManager().create()

2) How Can I initialize properties in the bundle ?

You can use register and activate OSGI service with properties http://wcm.io/testing/aem-mock/usage.html#Registering_OSGi_service for that. Here is some example


3) How Can I inject other service for my service ?

You can either Mock service or use register service API for that http://wcm.io/testing/aem-mock/usage.html#Registering_OSGi_service

Note that when you inject a service to your service using Reference then you have to register this your injected service, otherwise your test will fail.

4) How Can I test sling model ?

You can use aemContext for that. http://wcm.io/testing/aem-mock/usage.html#Sling_Models


Case 4: Writing test cases for AEM servlets and filters

This is very similar to how you would do test cases for Service. For request and response you either have to mock request / response object using Mockito or Use Spy  or use sling request and response mock. Since a lot of methods in filter and servlet do not return any result, Make Mockito verify your friend.  Here is one example using simple mockito to test servlet



 How can I measure my test coverage ?

 You can use jococo test coverage plugin along with your build system to measure this coverage. You can have following plugin in to your parent pom



How Can I write Integration test in AEM ?

Very good example here https://github.com/sneakybeaky/AEM-Integration-Test-Example

It is based of sling test base https://sling.apache.org/documentation/development/sling-testing-tools.html

I know this information is not enough to have you set up for writing tests in AEM. Feel free to let me know if you have more question and I will add more stuff here.

114 comments:

  1. Replies
    1. The effectiveness of IEEE Project Domains depends very much on the situation in which they are applied. In order to further improve IEEE Final Year Project Domains practices we need to explicitly describe and utilise our knowledge about software domains of software engineering Final Year Project Domains for CSE technologies. This paper suggests a modelling formalism for supporting systematic reuse of software engineering technologies during planning of software projects and improvement programmes in Project Centers in Chennai for CSE.

      Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
      Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai

      Delete
  2. Great Article… I love to read your articles because your writing style is too good, its is very very helpful. yoga teacher training in rishikesh

    ReplyDelete
  3. Hi DEAR..Thanks for sharing this post.I think it is a transcendent post. Such a wide number of an abundance of a dedication of appreciation is all together for this data. We Are Mobile Signal Booster
    get in touch with us for mobile network solution

    ReplyDelete
  4. Hi DEAR ...It was actually wonderful reading this info and I think you are absolutely right and I truly appreciate the article post thanks for sharing... WE are WYOXSPORTS
    weightlifting accessories contat us for all weightlifting accessories

    ReplyDelete
  5. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end. clark county detention center 24 hour bail bonds

    ReplyDelete
  6. This is a decent article here with some helpful hints for the individuals who are not used-to remark that much of the time. A debt of gratitude is in order for this accommodating data I concur with all focuses you have given to us. I will pursue every one of them.

    Astrologer In Jaipur
    Astrologer in Hyderabad
    black magic specialist in bangalore
    Vashikaran specialist in Mumbai
    Love marriage specialist in Delhi
    Vashikaran specialist in Delhi
    Best Astrologer in Delhi
    love marriage specialist
    Astrologer in Kolkata
    Love Marriage Specialist In Hyderabad

    ReplyDelete
  7. It has been essentially unfathomably liberal with you to give transparently what precisely numerous people would've promoted for an eBook to finish up making some money for their end, fundamentally given that you could have attempted it in the occasion you needed.
    Adopt Pets
    Adopt dogs near me
    Adopt cat near me

    ReplyDelete
  8. Great Article… I love to read your articles because your writing style is too good, its is very very helpful. yoga teacher training in rishikesh
    yoga ttc in rishikesh
    200 hours yoga teacher training in rishikesh

    ReplyDelete
  9. Hey Nice Blog!! Thanks For Sharing!!!Wonderful blog & good post.Its really helpful for me, waiting for a more new post. Keep Blogging!
    SEO company in coimbatore
    SEO company
    web design company in coimbatore

    ReplyDelete
  10. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end. if you are looking for satyanarayan puja please visit us.

    ReplyDelete
  11. Great Article… I love to read your articles because your writing style is too good, its is very very helpful. yoga teacher training in rishikesh

    ReplyDelete
  12. Hello DEAR ... I really value the article post a debt of gratitude is in order for sharing... WE are Free Jobs Notifications we are here to help candidates set up automatic monitoring for Bank of Baroda Recruitment

    ReplyDelete
  13. Zehra Global Services provides the best services Graphic Design, Software Development, Digital marketing and Mobile app development. It provides the best services to our customer.
    Mobile App Development
    Graphic Design
    Digital marketing

    ReplyDelete
  14. I found this article useful and looking forword for similar kind of blogs and if you want to know about TOP WEDDING PLANNERS CALGARY then u r at right place.

    ReplyDelete
  15. Nice blogs and eagerly waiting for such blogs and if you looking forword for Affordable Web Development Services then you are right place.

    ReplyDelete
  16. Nice blogs and eagerly waiting for such blogs and if you looking forword forTOP WEDDING PLANNERS CALGARY then u r at right place

    ReplyDelete
  17. "Extraordinary Article… I want to peruse your articles on the grounds that your composition style is excessively great, its is extremely useful. I really value the article post a debt of gratitude is in order for sharing... WE are Ayurvedic Herbs Products get in touch with us for all Buy Wellness Products Online , Buy Ayurvedic Herbs Online
    Buy Wellness Products"

    ReplyDelete
  18. Great post. I was once checking constantly this weblog and I'm impressed! Extremely useful information specially the closing part. I maintain such information much. I was once seeking this specific information for a very long time. Many thanks and best of luck you are looking for BEST NEWSMAGAZINE please visit us.

    ReplyDelete
  19. Greetings DEAR ...It was really magnificent perusing this information and I think you are totally right and I genuinely welcome the article post a debt of gratitude is in order for sharing... WE are Hazard Communication Training get in touch with us for Confined Space Entry Training , Heavy Equipment Training Program

    ReplyDelete
  20. Great post. I was once checking constantly this weblog and I'm impressed! Extremely useful information specially the closing part. I maintain such information much. I was once seeking this specific information for a very long time. Many thanks and best of luck you are looking for BEST NEWSMAGAZINE please visit us. BEST NEWSFEED SITE

    ReplyDelete
  21. I’m really happy to say it was an interesting post to read. I learned new information from your article, you are doing a great job. Continue. FAcebook , Twitter

    ReplyDelete
  22. CANIRA Website Development in usa , We are offering corporate Website Designing Service , give secure Web Solutions, Ecommerce Design, Apps Development, Digital Marketing and More

    ReplyDelete
  23. I’m really happy to say it was an interesting post to read. I learned new information from your article, you are doing a great job. Continue. Tips to increase stamina level Free , key to weight loss

    ReplyDelete
  24. Hi ! This is very informative & interesting article.Nice to read your blog post first time ever. I really appreciate this post. Thanks for sharing this awesome post if you are looking for Visitor Management System please visit us.

    ReplyDelete
  25. the best WordPress themes for business, blogging, and more. This accumulation of the Best Worpress Theme 2019 will enable you to build up a plan, Get your Best Matching Theme Now!

    On the off chance that u are Looking for another WordPress subject? Download the Best Wordpress Theme and layouts, Landing Page Templates , Free and Premium formats

    ReplyDelete
  26. Health is Wealth”, everyone have heard about this famous quote. When you have a healthy lifestyle, Lenalidomide Cost

    ReplyDelete
  27. This is a very elegantly composed post, my compliments. I am examining your post from the most punctual beginning stage, it was so captivating to voteize and I feel on account of you for posting such an OK blog, keep invigorates regularly. we are Designer Sarees Online

    ReplyDelete
  28. Thanks a lot for sharing this blog. I was searching for this topic for a while. Glad that I came across your blog. Great effort. Do share more.we are Wallpaper importer in Delhi

    ReplyDelete
  29. World's greatest astrologer Karan Sharma ji available at + 91-95777-44786 ; he is also Indian's best beneficial vashikaran expert for love and marriage.

    ReplyDelete
  30. I love to visit your site repeatedly because; here I find all information is very useful and educational for me.we are Interior Designer in Delhi

    ReplyDelete
  31. Thanks a lot for sharing this blog. I was searching for this topic for a while. Glad that I came across your blog. Great effort. Do share more.we are Wallpaper importer in Delhi

    ReplyDelete
  32. thanks for information if u want to know more aboutCalifornia Wineskindly visit us

    ReplyDelete
  33. This is a very elegantly composed post, my compliments. I am examining your post from the most punctual beginning stage, it was so captivating to voteize and I feel on account of you for posting such an OK blog, keep invigorates regularly. we are Beauty Parlour in Patiala Salon in Patiala

    ReplyDelete
  34. Nice blog..! Really very informative and creative contents. This concept is a good way to enhance the knowledge.Car Interior Cleaning Dubai-

    ReplyDelete
  35. thanks for information if u want to know more about kindly visit us :- Car Interior Cleaning Dubai

    ReplyDelete
  36. Shopclues here came up with an Offer where you can win special Shopclues Winner List 2019 by just playing a game & win prizes Call @6299249427
    Shopclues Winner List 2019
    Shopclues Winner List
    Shopclues Prize
    Prize Shopclues

    ReplyDelete
  37. We are providing Online Architectural Services, This is the most trustworthy site for planning application and building regulation drawings.

    ReplyDelete
  38. Really this information was helpful. I Got some good idea by reading this topic. Great information thanks for sharing this post. Land registry complience Plan

    ReplyDelete
  39. Ayurheals provides Best Ayurveda herbs online For Bedwetting or Diabetes with natural herbal remedies with Ayurvedic experts for diet and life style changes.Ayurvedic Herbs Online

    ReplyDelete
  40. Winner List Naaptol here came up with an Offer where you can win special Naaptol prize by just playing a game & win prizes Call @8404917617
    naaptol winner list 2020
    naaptol winner list
    naaptol winner name 2020
    naaptol winner name
    naaptol prize list
    naaptol lucky draw 2020

    ReplyDelete
  41. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end we are Online ayurveda

    ReplyDelete
  42. The information you shared was useful. You have brought up a very wonderful points , regards for the post.
    brother printer support | hp printer support| canon printer support

    ReplyDelete
  43. Great Article… I love to read your articles because your writing style is too good, its is very very helpful. we are washing machine repairs

    ReplyDelete
  44. Helpful article on importance of digital marketing, which is playing great role in promoting online business like vashikaran specialist in delhi and vashikaran specialist in Mumbai The business online are growing very rapidly like you can see vashikaran specialist in Chennaiare doing decent marketing. Also check vashikaran specialist in Bangalore for more knowledge.

    ReplyDelete
  45. for more astrological services we, Pandit Sairam is also a best indian astrologer in Toronto who has astrology going for walks in his blood and may offer all astrological solutions to your issues. You can get to know everything about your past, present and future life with this astrologer. famous indian astrologer in toronto | Top indian astrologer in toronto | indian astrologer in toronto | best indian astrologer in Toronto | famous astrologer in Toronto | Top astrologer in Toronto | Astrologer in Toronto

    ReplyDelete
  46. we are the best E-Commerce Website Developer in California.We make custom eCommerce destinations that convert guests into purchasers.

    ReplyDelete
  47. Packers and Movers Gurgaon Provide Reliable, Safe and Certified Service Provider list, Get Free ***Best Price Quotaition and Compare Charges. ???Hassle free Household Shifting Services, High Quality packing Material, Office Relocation, Car Transportaion, ###Local and Domestic Shifting Service @
    Packers And Movers Gurgaon

    ReplyDelete
  48. Black Magic Specialist in Mumbai

    https://www.bestlovevashikaranspecialists.com/black-magic-specialist-in-mumbai/

    Dark magic Specialist in Mumbai, India. One of the best ways to protect your family from Bad Evil Things only Dark magic can solve all of your problems even can help to get married soon.

    ReplyDelete
  49. Perfect Test House is a Leading Testing and Inspection Organization providing World Class Services of Condition Monitoring,Thermography, Leak Detection, Fire safety audit, Warehouse safery audit

    ReplyDelete
  50. http://cvslogin.bravesites.com/
    http://myhrcvss.yolasite.com/
    http://cvvsmyhr.emyspot.com/
    http://mycvvshr.simplesite.com
    https://myhrrcvs.page.tl/CVS-Pharmacy.htm
    customer plan individuals to fill their upkeep remedies through mail request conveyance or at a CVS Pharmacy retail location at a similar cost

    ReplyDelete
  51. CSHI Established in 2010, Canada Safe Haven Immigration Consulting is a Woodbridge based Canada Immigration Consultants Paralegal Consulting firm

    ReplyDelete
  52. Do you need a driver's license? do you need a second passport? do you need an ID?
    visit https://prolinedocs.com
    we provide registered passports, ID's & Driver's license for all countries.
    all the documents we process are registered in the specified database so our clients face no problems using our documents anywhere.
    Buy German driver's license online
    buy uk driver's license online
    buy european driver's license online
    buy uk passports online
    buy USA passports online
    buy canadian passports online
    WE PROVIDE WITH ANY DESIRED NATIONALITY
    we provide you 100 percent registered database documents.
    our service is well trusted over the world and have over 600 happy clients
    visit our website https://prolinedocs.com
    contact us via email: prolinedocs@protonmail.com
    contact us via whatsapp: +1(415)-326-4380

    ReplyDelete
  53. Best Return on investment Europe favorable and High Return investment plan in Europe for its Trading as well as stable and timely payouts. You can find a detailed description of our Trading packages in your back office cabinet.

    ReplyDelete
  54. We are a leading Website design company in Noida. We provide services like responsive website design, eCommerce websites and Wordpress Website Development.Website Design Company in Noida ,Website Design Company in India,Website Design Company in Delhi NCR

    ReplyDelete
  55. Perfect Test House is a Leading Testing and Inspection Organization providing World Class Services of Condition Monitoring,Thermography, Leak Detection, Fire safety audit, Warehouse safery audit

    ReplyDelete
  56. Famous astrologers have solutions to all the problems in your life. Hence he is called the famous astrologer in India. They give a love problem solution to people in a very short time. Therefore, if you also want to get some kind of love problem, love marriage problem, divorce problem, family problem solution then you should contact our famous astrologer MK Sharma today and get a solution to your problem.
    +91-9815389812

    ReplyDelete
  57. Keep up the great piece of work, I read few posts on this web site and I think that your blog is rattling interesting and has got bands of great information.
    Click here: design visiting card online

    ReplyDelete
  58. A person may have to go through the hair transplant surgery again depending on their hair loss. The patient will need to take regular medication to alleviate issues like pain, swelling and sore scalp. The medicines also help in reducing the risk of infection after the surgery. Further, medicines are also prescribed to improve the hair growth and stop future hair loss.
    Hair transplant in delhi
    best Hair transplant cost in delhi
    best Hair transplant in delhi
    Hair transplant clinic in delhi ncr
    Hair transplant clinic in near me
    Hair transplant for women in delhi

    ReplyDelete
  59. Online religion research paper writing services are very difficult to complete and many students are always searching for Religion Research Paper Services companies to help them complete their custom religion essay writing services.

    ReplyDelete
  60. There are academic nursing writing help companies whose ultimate goal is to provide Help with Nursing Writing Services since they are aware most nursing essay writing service part-time students lack enough time to complete their college custom nursing assignments.

    ReplyDelete
  61. Architectural science coursework writing help services have become very popular for students studying architectural science assignment writing services as they engage the best online Architectural Science Writing Services.

    ReplyDelete
  62. Online law research paper help services are very common nowadays since there are very many students seeking Law Research Writing Services and law essay writing services.

    ReplyDelete
  63. Hey Nice Blog!!
    Thanks For Sharing!!! Nice blog & Wonderfull post. Its really helpful for me, waiting for a more new post. Keep on posting!


    starting business
    business ideas
    small business ideas

    ReplyDelete
  64. 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. i am also a blogger and corrently working on professional translation and localization services if any one here who need any help please visit us. Thanks

    ReplyDelete
  65. We provide a platform where users can search Top lawyers of india. Clients can raise a query and get free legal advice from the Best Advocates in India. Apart from being useful for users to search lawyers and seeking legal advice, this website serves as an attractive marketing platform for advocates free of cost. A platform where clients can search and meet Top Advocates of their city and Best Lawyers in India and get free legal advice online.

    ReplyDelete
  66. Codeaxia Digital Solutions is a digital agency based out of Delhi/NCR. We provide valuable & economical digital solutions for the customers in areas such as website designing, development & maintenance, graphic designing, digital marketing and mobile applications development.
    Codeaxia provides best solutions -
    Responsive Web Designing
    SEO Ready Web Development
    Ecommerce Website Development
    ROI Focussed Digital Marketing

    ReplyDelete
  67. how to get slim without exercise | Get Skinny in a Week, Read on for tips and deceives on to get Slim Body Without Exercise, These simple strategies will help you lose weight without exercise. Slim Body Without Exercise

    ReplyDelete
  68. Hi!!!
    Hey Wonder full Blog! Thanks for this valuable Information Sharing with us your review is very nice.
    Thanks once again for this Wonderful article. Waiting for a more new post
    Keep on posting!

    web development company in Coimbatore
    web design company in Coimbatore
    website development company in Coimbatore
    website designing company in India

    ReplyDelete
  69. If you are looking for the best digital marketing company in delhi ? Adopt Digital is leading one of the best Digital Marketing Company in Delhi, India" internet marketing

    ReplyDelete
  70. Book Private Jet Charter : Foresee Aviation India’s leading Private Aircraft and Helicopter Charter company offers helicopter charter, Cargo charter, private jet and executive airliner charters in India. Helicopter Charter company in india

    ReplyDelete
  71. Linguidoor is a professional translation services that offer professional translation and Localization services in 50 languages. Document Translation services" Translation services company

    ReplyDelete
  72. how to get slim without exercise | Get Skinny in a Week, Read on for tips and deceives on to get Slim Body Without Exercise, These simple strategies will help you lose weight without exercise. Slim Body Without Exercise

    ReplyDelete
  73. only4pets Online Store is Designed for agriculturists and buy pet online in india. Pet Lovers to Sell/Buy Their Animals/Birds From Home the costs are best in the market and additionally different installment modes likewise accessible.dogs for sale near me

    ReplyDelete
  74. About lucky draw and prizes
    Lucky draw and lotteries are always a sight of attraction and someway fascinate us to participate in it and try our luck to hit the perfect shot. This lucky draw coupon makes us so much excited that sometimes we are driven to provide them with all the information or make payments for Lucky Draw Complaint Contest and lottery.

    But have you ever bothered that these lucky draw coupons can be a scam or fraud with you……….Just think !!!.
    We are here to provide you with the solution to check out whether this particular lucky draw is fake or not.

    We are here to help you out. This is a platform where consumers can do an inquiry about the contacted company and would get to know the details of lucky draw and lottery. Here, we help costumers to come forward with their queries, and our expert team will always be there for you and provide you an immediate response from our side. https://enquirycomplaints.co.in/

    ReplyDelete
  75. Shopclues Lucky draw scratch card
    Dear Customer, If you got any Shopclues Lucky Draw Scratch Card and wanted to know it’s really working or not, then contact us. Shopclues is not running any kind of contest now. We will let you know if there is any contest. Shopclues lucky draw, Shopclues lucky draw winner list, Shopclues lucky draw winner 2020, Shopclues Winner list, Shopclues winner list 2020, Snapdeal lucky draw, Snapdeal lucky draw winner list, Snapdeal lucky draw winner 2020, Snapdeal winner list, Kbc lottery, Kbc lottery winner 2021, Kbc lottery winner list, Rock johnson lottery winner 2020, Rock Johnson winner list ,Rock johnson lottery https://shopcluesluckydrawlist.com/

    ReplyDelete
  76. Linguidoor is a professional translation services that offer professional translation and Localization services in 50 languages. Document Translation services" Translation services company

    ReplyDelete
  77. Book Private Jet Charter : Foresee Aviation India’s leading Private Aircraft and Helicopter Charter company offers helicopter charter, Cargo charter, private jet and executive airliner charters in India. Helicopter Charter company in india

    ReplyDelete
  78. We provide the best b2b lead generation services based on your target industry, geography Our leads are well qualified for sales appointments, Best B2B Lead Generation Strategies

    ReplyDelete
  79. Thanks for sharing the important and awesome information, Thank you. SEO Services in Delhi

    ReplyDelete
  80. Great Article… I love to read your articles because your writing style is too good, its is very very helpful.
    Natural gemstone

    ReplyDelete