2012/09/15

How to automate tests with Groovy 2.0, Spock and Gradle

This is the launch of the 1st blog in my life, so cheers and have a nice reading!

y u no test?

Couple of years ago I wasn't a big fan of unit testing. It was obvious to me that well prepared unit tests are crucial though. I didn't known why exactly crucial yet then. I just felt they are important. My disliking to write automation tests was mostly related to the effort necessary to prepare them. Also a spaghetti code was easily spotted in test sources.

Some goodies at hand

Now I know! Test are crucial to get a better design and a confidence. Confidence to improve without a hesitation. Moreover, now I have the tool to make test automation easy as Sunday morning... I'm talking about the Spock Framework. If you got here probably already know what the Spock is, so I won't introduce it. Enough to say that Spock is an awesome unit testing tool which, thanks to Groovy AST Transformation, simplifies creation of tests greatly.

An obstacle

The point is, since a new major version of Groovy has been released (2.0), there is no matching version of Spock available yet.

What now?

Well, in a matter of fact there is such a version. It's still under development though. It can be obtained from this Maven repository. We can of course use the Maven to build a project and run tests. But why not to go even more "groovy" way? XML is not for humans, is it? Lets use Gradle.

The build file

Update: at the end of the post is updated version of the build file.
apply plugin: 'groovy'
apply plugin: 'idea'

def langLevel = 1.7

sourceCompatibility = langLevel
targetCompatibility = langLevel

group = 'com.tamashumi.example.testwithspock'
version = '0.1'

repositories {
    mavenLocal()
    mavenCentral()
    maven { url 'http://oss.sonatype.org/content/repositories/snapshots/' }
}

dependencies {
    groovy 'org.codehaus.groovy:groovy-all:2.0.1'
    testCompile 'org.spockframework:spock-core:0.7-groovy-2.0-SNAPSHOT'
}

idea {
    project {
        jdkName = langLevel
        languageLevel = langLevel
    }
}
As you can see the build.gradle file is almost self-explanatory. Groovy plugin is applied to compile groovy code. It needs groovy-all.jar - declared in version 2.0 at dependencies block just next to Spock in version 0.7. What's most important, mentioned Maven repository URL is added at repositories block.

Project structure and execution

Gradle's default project directory structure is similar to Maven's one. Unfortunately there is no 'create project' task and you have to create it by hand. It's not a big obstacle though. The structure you will create will more or less look as follows:
<project root>
│
├── build.gradle
└── src
    ├── main
    │   ├── groovy
    └── test
        └── groovy
To build a project now you can type command gradle build or gradle test to only run tests.

How about Java?

You can test native Java code with Spock. Just add src/main/java directory and a following line to the build.gradle:
apply plugin: 'java'
This way if you don't want or just can't deploy Groovy compiled stuff into your production JVM for any reason, still whole goodness of testing with Spock and Groovy is at your hand.

A silly-simple example

Just to show that it works, here you go with a basic example.

Java simple example class:

public class SimpleJavaClass {

    public int sumAll(int... args) {

        int sum = 0;

        for (int arg : args){
            sum += arg;
        }

        return sum;
    }
}

Groovy simple example class:

class SimpleGroovyClass {

    String concatenateAll(char separator, String... args) {

        args.join(separator as String)
    }
}

The test, uhm... I mean the Specification:

class JustASpecification extends Specification {

    @Unroll('Sums integers #integers into: #expectedResult')
    def "Can sum different amount of integers"() {

        given:
            def instance = new SimpleJavaClass()

        when:
            def result = instance.sumAll(* integers)

        then:
            result == expectedResult

        where:
            expectedResult | integers
            11             | [3, 3, 5]
            8              | [3, 5]
            254            | [2, 4, 8, 16, 32, 64, 128]
            22             | [7, 5, 6, 2, 2]
    }

    @Unroll('Concatenates strings #strings with separator "#separator" into: #expectedResult')
    def "Can concatenate different amount of integers with a specified separator"() {

        given:
            def instance = new SimpleGroovyClass()

        when:
            def result = instance.concatenateAll(separator, * strings)

        then:
            result == expectedResult

        where:
            expectedResult     | separator   | strings
            'Whasup dude?'     | ' ' as char | ['Whasup', 'dude?']
            '2012/09/15'       | '/' as char | ['2012', '09', '15']
            'nice-to-meet-you' | '-' as char | ['nice', 'to', 'meet', 'you']
    }
} 
To run tests with Gradle simply execute command gradle test. Test reports can be found at <project root>/build/reports/tests/index.html and look kind a like this.


Please note that, thanks to @Unroll annotation, test is executed once per each parameters row in the 'table' at specification's where: block. This isn't a Java label, but a AST transformation magic.

IDE integration

Gradle's plugin for Iintellij Idea

I've added also Intellij Idea plugin for IDE project generation and some configuration for it (IDE's JDK name). To generate Idea's project files just run command: gradle idea There are available Eclipse and Netbeans plugins too, however I haven't tested them. Idea's one works well.

Intellij Idea's plugins for Gradle

Idea itself has a light Gradle support built-in on its own. To not get confused: Gradle has plugin for Idea and Idea has plugin for Gradle. To get even more 'pluginated', there is also JetGradle plugin within Idea. However I haven't found good reason for it's existence - well, maybe excluding one. It shows dependency tree. There is a bug though - JetGradle work's fine only for lang level 1.6. Strangely all the plugins together do not conflict each other. They even give complementary, quite useful tool set.

Running tests under IDE

Jest to add something sweet this is how Specification looks when run with jUnit  runner under Intellij Idea (right mouse button on JustASpecification class or whole folder of specification extending classes and select "Run ...". You'll see a nice view like this.

Building web application

If you need to build Java web application and bundle it as war archive just add plugin by typing the line
apply plugin: 'war'
in the build.gradle file and create a directory src/main/webapp.

Want to know more?

If you haven't heard about Spock or Gradle before or just curious, check the following links:

What next?

The last thing left is to write the real production code you are about to test. No matter will it be Groovy or Java, I leave this to your need and invention. Of course, you are welcome to post a comments here. I'll answer or even write some more posts about the subject.

Important update

Spock version 0.7 has been released, so the above build file doesn't work anymore. It's easy to fix it though. Just remove last dash and a word SNAPSHOT from Spock dependency declaration. Other important thing is that now spock-core depends on groovy-all-2.0.5, so to avoid dependency conflict groovy dependency should be changed from version 2.0.1 to 2.0.5.
Besides oss.sonata.org snapshots maven repository can be removed. No obstacles any more and the build file now looks as follows:
apply plugin: 'groovy'
apply plugin: 'idea'

def langLevel = 1.7

sourceCompatibility = langLevel
targetCompatibility = langLevel

group = 'com.tamashumi.example.testwithspock'
version = '0.1'

repositories {
    mavenLocal()
    mavenCentral()
}

dependencies {
    groovy 'org.codehaus.groovy:groovy-all:2.0.5'
    testCompile 'org.spockframework:spock-core:0.7-groovy-2.0'
}

idea {
    project {
        jdkName = langLevel
        languageLevel = langLevel
    }
}

99 comments:

  1. Thanks for this tips. http://www.fuoye.edu.ng

    ReplyDelete
  2. The future of software testing is on positive note. It offers huge career prospects for talented professionals to be skilled software testers. Best software testing training institute in Chennai | Software Testing Training in Chennai | Software testing course in Chennai

    ReplyDelete
  3. Hi, thanks for sharing such an informative blog. I have read your blog and I gathered some needful information from your blog. Keep update your blog. Awaiting for your next update. Selenium Training in Chennai

    ReplyDelete
  4. Hi, I am really happy to found such a helpful and fascinating post that is written in well manner. Thanks for sharing such an informative post. QTP Training in Chennai

    ReplyDelete
  5. Thanks for your informative article on UFT automation testing tool. Your post helped me to understand the features and functionality of QTP automation testing tool. QTP Training in Chennai | QTP training Chennai

    ReplyDelete
  6. Really awesome blog. Your blog is really useful for me.
    Thanks for sharing this informative blog. Keep update your blog.
    Oracle Training In Chennai

    ReplyDelete
  7. Twilio woocommerce plugin That Boost your business Best Plugin for online stores and for advertising

    ReplyDelete
  8. I am searching for dependable responsive web design services. In the event that you have any thought regarding driving organizations then told me?

    ReplyDelete
  9. this software is new to me but it is really a good job i thank for this posting it is nice .


    software testing training in chennai

    ReplyDelete
  10. Thanks for your informative post on selenium automation testing tool. Your article helped me a lot in understanding the future of automation testing tool and its career prospects. Selenium Training | Best Selenium training institute in Chennai

    ReplyDelete
  11. Very helpful post thanks for useful sharing local marketing seo

    ReplyDelete


  12. Really very nice blog information for this one and more technical skills are improve,i like that kind of post.



    SAP training in Chennai

    ReplyDelete
  13. I read your post, learned new informations. Thanks for sharing.

    eCommerce web development services in Chennai

    ReplyDelete
  14. very good information
    http://hadooptraininginhyderabad.co.in/salesforce-training-in-hyderabad/

    ReplyDelete
  15. لدينا مميزات في خدمات كشف تسربات التي تقدمها شركة ركن البيت التي تكون متخصصة فيها فتعاملك مع شركة كشف تسربات المياه بالدمام لديها امكانيات جيدة يساعدك علي التخلص من مشاكل التسريب التي توجد لديك بسهولة دون التعرض للخطر حيث نمتلك في شركة كشف تسربات بالدمام الامكانيات والفنين المتميزين الذين يقدمون الخدمة بتميز فاذا كنت فى حيرة من امر التسريب الذي يوجد لديك فعليك ان تعلم ان خدماتنا منتشرة في جميع انحاء المملكة مثل خدمات شركة كشف تسربات المياه بالرياض التي تحل لك المشاكل المتكررة المتعلقة بالتسربات فلا داعى للقلق من الان لانك سوف تملك فني جيد منزلك يحل لك كل مشاكل التسربات و كيفية القيام بهذه الخدمة وتذكر ان الحل الامثل فى شركة كشف تسربات بالرياض ان توفر كل الامكانيات التى تساعدك علي حل مشكلاتك

    ReplyDelete
  16. Your content is awesome . You have done a great job and its very useful for me . I appreciate your effort and I hope that you will get more positive comments from the web users.
    SMO Services Chennai

    ReplyDelete
  17. Great post. I like your blog. Thanks for sharing.

    web design courses in chennai

    ReplyDelete
  18. Great post! Keep sharing such a informative post.

    digital marketing training in chennai

    ReplyDelete
  19. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Java Training in Chennai | Core Java Training in Chennai

    ReplyDelete
  20. Thanks for Sharing the valuable information and thanks for sharing the wonderful article..We are glad to see such a wonderful article..
    QTP Training in Chennai | QTP Training Institute in Chennai | QTP Training

    ReplyDelete
  21. Wonderful post. Keep sharing such a useful post.

    php training in chennai

    ReplyDelete
  22. Wonderful post. Keep sharing such a useful post.
    R programming training in chennai

    ReplyDelete
  23. Great post! Keep sharing such a informative post.
    SAS training in chennai

    ReplyDelete
  24. This was so useful in building our site. The article helped me to learn something new.

    Premium Digital Marketing Course Chennai

    ReplyDelete
  25. its really helpful for beginners i have also have some info about web design companies

    ReplyDelete
  26. Great Explanation. Really its helps a lot and is working!! Thanks buddy. Selenium is one of the best automation. Check out some of the best selenium concepts which can help you as well.Best Selenium training in Chennai | Selenium testingtraining institute in Chennai

    ReplyDelete
  27. Thanks for your informative article on Gradle build automation. Your post helped me to understand the features and functionality of Gradle. selenium training in chennai || Best Selenium Testing training in chennai

    ReplyDelete
  28. Our Digital Marketing Training is tailored for beginners who want to learn how to stand out digitally, whether it is for their own business or a personal brand.

    digital marketing course

    ReplyDelete

  29. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Android Training in Chennai
    Ios Training in Chennai

    ReplyDelete

  30. You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...

    Android App Development Company

    ReplyDelete
  31. The blog gave me idea to automate test with groovy My sincere thanks for sharing this post and please continue to share this post
    Software Testing Training in Chennai

    ReplyDelete
  32. really nice blog has been shared by you. before i read this blog i didn't have any knowledge about this but now i got some knowledge.
    software testing training in chennai

    ReplyDelete
  33. This point of Groovy is a major version software to have the release of new version 2.0. It's best to update version of the Groovy software.If want become to learn for Java Training To reach us, Java Training in Chennai | Java Training in Chennai

    ReplyDelete
  34. Its an amazing post. I have learnt lots of new information from your blog. Keep sharing. Thank you... Selenium Training in Chennai | Software Testing Training in Chennai

    ReplyDelete
  35. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing..
    iOS App Development Company
    iOS App Development Company

    ReplyDelete
  36. These ways are very simple and very much useful, as a beginner level these helped me a lot thanks fore sharing these kinds of useful and knowledgeable information.
    Fitness SMS
    Fitness Text
    Salon SMS
    Salon Text
    Investor Relation SMS
    Investor Relation Text
    Mobile Marketing Services
    mobile marketing companies
    Sms API

    ReplyDelete
  37. This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Mobile Marketing Service
    Mobile Marketing Companies
    Sms API
    Texting API
    sms marketing

    ReplyDelete
  38. Hi Friend Your Blog is Very Nice
    Mann Tours is Best Tours offer Provider and Best Travel Company in India, Tour Package India and Travel Package in Delhi Enjoy by all Historical Place and Temple with all Luxury Car and Bus, Volvo, Coach Best Services Provide for all India Events and Tours 24*7 Hours Booking Now
    Travel Package in Delhi

    ReplyDelete
  39. This article is very much helpful and i hope this will be an useful information for the needed one. Keep on updating these kinds of informative things...
    Texting API
    Text message marketing
    Digital Mobile Marketing
    Mobile Marketing Services
    Mobile marketing companies
    Fitness SMS

    ReplyDelete
  40. This is mainly used for the treatment of stress headache. order fioricet with visa

    ReplyDelete
  41. I agree. I have tried to do everything for 50 years and the only thing that allows me to work till then.Order Fioricet Online Cod

    ReplyDelete
  42. Thanks for your marvelous posting! It is very useful and good. Come on. I want to introduce an get app installs, I try it and I feel it is so good to rank app to top in app store search results, have you ever heard it?

    ReplyDelete
  43. Excellent. Thank you very much for this awesome list.

    ReplyDelete
  44. Adipex helps a lot in weight lossand it shows great results.

    ReplyDelete
  45. Excellent read, Positive site, where did u come up with the information on this posting? I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work

    PSD to Wordpress
    wordpress website development

    ReplyDelete
  46. Thanks for such a knowledgeable post.We provide Best SEO services in Chennai
    digital marketing classes in chennai

    ReplyDelete
  47. https://stitchclothes.com here we stitch clothes as per your design and selection

    ReplyDelete
  48. https://stitchclothes.com here we stitch clothes as per your design and selection

    ReplyDelete
  49. There is some painkiller medication on these website that gives relief to the pain in minutes, just click on the website and enjoy it.

    ReplyDelete
  50. These websites provide a very good service and the results of all the medicines available here are very good. From here you can easily buy medicines.

    ReplyDelete
  51. Everyone wants to get unique place in the IT industry’s for that you need to upgrade your skills, your blog helps me improvise my skill set to get good career, keep sharing your thoughts with us.
    software testing course in chennai

    ReplyDelete
  52. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
    Java Training Institute Bangalore

    Best Java Training Institute Chennai


    ReplyDelete
  53. Thanks for the useful information of software testing courses, give more updates on software testing development, First time I visit your blog really nice, I bookmark your blog here after a daily visit. Learn software testing course in Chennai

    ReplyDelete
  54. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.

    Best Hadoop Training in Chennai

    ReplyDelete

  55. Thankyou for sharing this good information.hadoop training in chennai

    ReplyDelete
  56. Thanks for the blog and it is really very useful one.hadoop training in chennai

    ReplyDelete
  57. 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.
    Data Science Training in Chennai
    Data science training in bangalore
    Data science online training

    ReplyDelete
  58. 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.
    Devops training in Chennai
    Devops training in Bangalore
    Devops training in Pune
    Devops Online training
    Devops training in Pune
    Devops training in Bangalore
    Devops training in tambaram

    ReplyDelete
  59. I am commenting to let you know what a terrific experience my daughter enjoyed reading through your web page. She noticed a wide variety of pieces, with the inclusion of what it is like to have an awesome helping style to have the rest without hassle grasp some grueling matters.


    ccna training in chennai



    ccna training in bangalore


    ccna training in pune

    ReplyDelete
  60. Outstanding blog post, I have marked your site so ideally I’ll see much more on this subject in the foreseeable future.
    java training in chennai | java training in bangalore

    java online training | java training in pune

    selenium training in chennai

    selenium training in bangalore

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

    ReplyDelete
  62. I would like to thank you for your nicely written post, its informative and your writing style encouraged me to read it till end. Thanks

    angularjs-Training in annanagar

    angularjs Training in chennai

    angularjs Training in chennai

    angularjs Training in bangalore

    ReplyDelete
  63. Hello! This is my first visit to your blog! We are a team of volunteers and starting a new initiative in a community in the same niche. Your blog provided us useful information to work on. You have done an outstanding job.


    AWS Training in Rajaji Nagar | Amazon Web Services Training in Rajaji Nagar


    Amazon Web Services Training in Pune | Best AWS Training in Pune

    AWS Online Training | Online AWS Certification Course - Gangboard

    ReplyDelete
  64. I simply want to give you a huge thumbs up for the great info you have got here on this post.
    python training in velachery
    python training institute in chennai

    ReplyDelete
  65. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

    Devops Training in pune
    DevOps online Training

    ReplyDelete
  66. Read all the information that i've given in above article. It'll give u the whole idea about it.
    Selenium Training in Chennai | Selenium Training in Bangalore |Selenium Training in Pune | Selenium online Training

    ReplyDelete
  67. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..

    angularjs online Training

    angularjs Training in marathahalli

    angularjs interview questions and answers

    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs Training in chennai

    ReplyDelete
  68. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
    Best Devops Training in pune | Java training in Pune

    ReplyDelete
  69. Very good brief and this post helped me alot. Say thank you I searching for your facts. Thanks for sharing with us!

    python training in chennai | python course institute in chennai | Data Science Interview questions and answers

    ReplyDelete
  70. When I initially commented, I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the same comment. Is there any way you can remove people from that service? Thanks.

    Advanced AWS Interview Questions And Answers

    Advanced AWS Training in Chennai | Best AWS Training in Chennai

    Advanced AWS Training in Pune | Best Amazon Web Services Training in Pune

    ReplyDelete
  71. If you want to see the best group buy SEO tools in one place, then you’ll LOVE this page
    we personally provide you best and cheapest group buy seo tools just 9 euro per month.https://www.groupbuyseotools.net/best-seo-group-buy-tools-2018/
    #groupbuyseotools #seotoolsgroupbuy #seotools #ahrefs #semrush #bestseotools

    ReplyDelete
  72. Best explanation ever, previously I was looking for a info about this technology and now I am Clear. Thanks
    FITA
    Selenium Training in Chennai
    Selenium Training in Velachery
    Selenium Training in Tambaram

    ReplyDelete