Sunday, December 4, 2016

Using groovy for tests

While I already has some exposure to dynamic languages - also those working under control of JVM, until now I had not touched Groovy, despite its presence on JUG meetings, conferences etc. I could of course see lot of value in tools like Spock, Geb or recently popular Gradle. However that was for me more a nice-to-have, rather than a must.
So with pleasure I am now discovering really nice points of using Groovy - as language that powers the tests and complements the Java main sources. It turns out that even with no frameworks mentioned above, you can benefit just from using Groovy in your test. Here are the reasons:
  1. You already know almost all of syntax. Old good Java code will probably just work. It is not like JavaScript, which is similar to Java just in name. Rest things you need you can find in documentation - which is quite good and answers most of my questions.
  2. Forget semicolons, alias imported objects, use list and map literals, multiline strings, use def. Almost like Scala.
  3. No more @VisibleForTesting. Groovy allows you to break object members visibility. Maybe it is not best idea to look into internal state of objects, but now you can. At least tested methods do not need to be kept in package visibility.
  4. Power assert. This looks just like Java assert. But output on your console when there is a failure... I just love this feature. Just take a look:
    Assertion failed:
    assert apiResponse.code() >= 200 && apiResponse.code() < 300
           |           |      |      |  |           |      |
           |           404    true   |  |           404    false
           |                         |  retrofit2.Response@42d0a255
           |                         false
  5. BigDecimal everywhere. 42.0 is not a float any longer. If your code has something in common with money you can feel relief.
  6. @TypeChecked. Why not just use compiler? With Groovy you can! It is so nice when machine corrects your errors.
I am not convinced whether Groovy is language of future :> But definitely worth trying.