Groovy tips

How to execute closure more than once ?

It can be done with times method: @Test void "should execute closure twice"() { int i = 0 2.times { i++ } assertThat(i).isEqualTo(2) } Another method is upto which execute...

Continue Reading β†’

How to initialize map with default values ?

Sometimes, when we don't know the value for given entry, we can use a default value. In Java, it would be done at entry adding: public String getLetter(String key) { String letter = letters.get(...

Continue Reading β†’

How to define String containing slashes and quotes ?

In Groovy we can use a special String construction called slashy String. It allows us to construct String object containing as well quotes as slashes, without the need of escaping them manualy. Let's ...

Continue Reading β†’

How to get content of URI resource (file, website) ?

To get content of file or website, we can simply use getText() method applied as well for File class, as for URL. @Test void "should correctly read web page to String"() { def url = "http://w...

Continue Reading β†’

How to read file content from classpath ?

To get a content of file from classpath, we can use the mix of getClass() and getText methods: @Test void "should correctly load file content from classpath"() { // sample_file.txt located in /...

Continue Reading β†’

How to convert List to Map ?

Collections conversion in Groovy can be achieved with some of collect* features. One of them, collectEntries(), iterates through given collection and returns a key-value pair. This pair is after store...

Continue Reading β†’