Posts by Hubert Klein Ikkink

Checking Parameters Mock Method Invocation in Spock

Posted on by  
Hubert Klein Ikkink

Arthur Arts wrote an blog post about Using ArgumentCaptor for generic collections with Mockito. With the ArgumentCaptor in Mockito the parameters of a method call to a mock are captured and can be verified with assertions. In Spock we can also get a hold on the arguments that are passed to a method call of a mock and we can write assertions to check the parameters for certain conditions. When we create a mock in Spock and invoke a method on the mock the arguments are matched using the equals() implementation of the argument type. If they are not equal Spock will tell us by showing a message that there are too few invocations of the method call. Let’s show this with an example. First we create some classes we want to test:

package com.jdriven.spock

class ClassUnderTest {

    private final Greeting greeting

    ClassUnderTest(final Greeting greeting) {
        this.greeting = greeting
    }

    String greeting(final List<Person> people) {
        greeting.sayHello(people)
    }
}

package com.jdriven.spock

interface Greeting {
    String sayHello(final List<Person> people)
}

package com.jdriven.spock

@groovy.transform.Canonical
class Person {
    String name
}

Continue reading →

Change return value of mocked or stubbed service based on argument value with Spock

Posted on by  
Hubert Klein Ikkink

Albert van Veen wrote a blog post about Using ArgumentMatchers with Mockito. The idea is to let a mocked or stubbed service return a different value based on the argument passed into the service. This is inspired me to write the same sample with Spock. Spock already has built-in mock and stub support, so first of all we don’t need an extra library to support mocking and stubbing. We can easily create a mock or stub with the Mock() and Stub() methods. We will see usage of both in the following examples. In the first example we simply return true or false for ChocolateService.doesCustomerLikesChocolate() in the separate test methods.

import spock.lang.*

public class CandyServiceSpecification extends Specification {

    private ChocolateService chocolateService = Mock()
    private CandyService candyService = new CandyServiceImpl()

    def setup() {
        candyService.chocolateService = chocolateService
    }

    def "Customer Albert really likes chocolate"() {
        given:
        final Customer customer = new Customer(firstName: 'Albert')

        and: 'Mock returns true'
        1 * chocolateService.doesCustomerLikesChocolate(customer) >> true

        expect: 'Albert likes chocolate'
        candyService.getCandiesLikeByCustomer(customer).contains Candy.CHOCOLATE
    }

    def "Other customer do not like chocolate"() {
        given:
        final Customer customer = new Customer(firstName: 'Any other firstname')

        and: 'Mock returns false'
        1 * chocolateService.doesCustomerLikesChocolate(customer) >> false

        expect: 'Customer does not like chocolate'
        !candyService.getCandiesLikeByCustomer(customer).contains(Candy.CHOCOLATE)
    }

}

Continue reading →

How to test for an exception with Spock

Posted on by  
Hubert Klein Ikkink

Willem Cheizoo already wrote an blog post about How to test for an exception with JUnit and this inspired me to write the same sample with Spock. In Spock we can use the thrown() method to check for exceptions. We can use it in a then: block of our test.

import spock.lang.*

public class JDrivenServiceSpecification extends Specification {

    private JDrivenService service = new JDrivenService()

    def "publishArticle throws ArticleNotFoundException() {
        when:
        service.publishArticle null

        then:
        final ArticleNotFoundException exception = thrown()
        // Alternate syntax: def exception = thrown(ArticleNotFoundException)

        exception.message == 'Article not found please provide an article to publish'
    }

}

Continue reading →

Grails Goodness: Using Wrapper for Running Grails Commands Without Grails Installation

Posted on by  
Hubert Klein Ikkink

Since Grails 2.1 we can create a Grails wrapper. The wrapper allows developer to run Grails commands in a project without installing Grails first. The wrapper concept is also available in other projects from the Groovy ecosystem like Gradle or Griffon. A wrapper is a shell script for Windows, OSX or Linux named grailsw.bat or grailsw and a couple of JAR files to automatically download a specific version of Grails. We can check in the shell scripts and supporting files into a version control system and make it part of the project. Developers working on the project simply check out the code and execute the shell script. If there is no Grails installation available then it will be downloaded. To create the shell scripts and supporting files someone on the project must run the wrapper command for the first time. This developer must have a valid Grails installation. The files that are generated can then be added to version control and from then one developers can use the grailsw or grailsw.bat shell scripts.

$ grails wrapper
| Wrapper installed successfully
$

Continue reading →

Grails Goodness: Set Property Values of Spring Beans in resources.groovy

Posted on by  
Hubert Klein Ikkink

We can configure Spring beans using several methods in Grails. We can for example add them to grails-app/conf/spring/resources.xml using Spring’s XML syntax. But we can also use a more Groovy way with grails-app/conf/spring/resources.groovy. We can use a DSL to define or configure Spring beans that we want to use in our Grails application. Grails uses BeanBuilder to parse the DSL and populate the Spring application context. To define a bean we use the following syntax beanName(BeanClass). If we want to set a property value for the bean we use a closure and in the closure we set the property values. Let’s first create a simple class we want to configure in the Spring application context:

// File: src/groovy/com/mrhaki/spring/Person.groovy
package com.mrhaki.spring

import groovy.transform.ToString

@ToString
class Person {
    String name
    Date birthDate
}

Continue reading →

Grails Goodness: Injecting Grails Services into Spring Beans

Posted on by  
Hubert Klein Ikkink

One of the underlying frameworks of Grails is Spring. A lot of the Grails components are Spring beans and they all live in the Spring application context. Every Grails service we create is also a Spring bean and in this blog post we see how we can inject a Grails service into a Spring bean we have written ourselves. The following code sample shows a simple Grails service we will inject into a Spring bean:

// File: grails-app/services/com/mrhaki/sample/LanguageService.groovy
package com.mrhaki.sample

class LanguageService {

    List<String> languages() {
        ['Groovy', 'Java', 'Clojure', 'Scala']
    }

}

Continue reading →

Using URL Scheme for Telephone Numbers in HTML

Posted on by  
Hubert Klein Ikkink

We can use the tel: URL scheme for phone numbers in HTML. Just like the mailto: URL scheme will open the default mail application will the tel: start a telephone call. If the HTML page is viewed on a mobile phone and we select a link with the tel: scheme we can immediately call the number following the scheme. On a desktop computer a VOIP call will be initiated.

We can use hyphens in the phone number for readability, they will be ignored when the call is made. For example the imaginary phone number 123456789 in the Netherlands can be used as shown in the following HTML snippet:

Continue reading →

Gradle Goodness: Distribute Custom Gradle in Our Company

Posted on by  
Hubert Klein Ikkink

The Gradle wrapper allows us to let developers use Gradle without the need for every developer to install Gradle. We can add the output of the Gradle wrapper task to version control. Developers only need to checkout the source for a project and invoke the gradlew or gradlew.bat scripts. The scripts will look for a Gradle distribution and download it to the local computer of a developer. We can customize the Gradle wrapper and provide a different source for the Gradle distribution. For example we can add the Gradle distribution ZIP file on our company intranet. We then use the distributionUrl property of the Wrapper task to reference the intranet location where we place the Gradle distribution ZIP file.

In the following sample file we use the distributionUrl property to reference our company intranet:

Continue reading →

Groovy Goodness: Pretty Print XML

Posted on by  
Hubert Klein Ikkink

The easiest way to pretty print an XML structure is with the [XmlUtil](http://groovy.codehaus.org/api/groovy/xml/XmlUtil.html) class. The class has a serialize() method which is overloaded for several parameter types like String, GPathResult and Node. We can pass an OutputSteam or Writer object as argument to write the pretty formatted XML to. If we don't specify these the serialize() method return a String value.

import groovy.xml.*

def prettyXml = '''
<?xml version="1.0" encoding="UTF-8"?>
<languages>
  <language id="1">Groovy</language>
  <language id="2">Java</language>
  <language id="3">Scala</language>
</languages>
'''


// Pretty print a non-formatted XML String.
def xmlString = '<languages><language id="1">Groovy</language><language id="2">Java</language><language id="3">Scala</language></languages>'
assert XmlUtil.serialize(xmlString) == prettyXml

// Use Writer object as extra argument.
def xmlOutput = new StringWriter()
XmlUtil.serialize xmlString, xmlOutput
assert xmlOutput.toString() == prettyXml

// Pretty print a Node.
Node languagesNode = new XmlParser().parseText(xmlString)
assert XmlUtil.serialize(languagesNode) == prettyXml


// Pretty print a GPathResult.
def langagesResult = new XmlSlurper().parseText(xmlString)
assert XmlUtil.serialize(langagesResult) == prettyXml


// Pretty print org.w3c.dom.Element.
org.w3c.dom.Document doc = DOMBuilder.newInstance().parseText(xmlString)
org.w3c.dom.Element root = doc.documentElement
assert XmlUtil.serialize(root) == prettyXml


// Little trick to pretty format
// the result of StreamingMarkupBuilder.bind().
def languagesXml = {
    languages {
        language id: 1, 'Groovy'
        language id: 2, 'Java'
        language id: 3, 'Scala'
    }
}
def languagesBuilder = new StreamingMarkupBuilder()
assert XmlUtil.serialize(languagesBuilder.bind(languagesXml)) == prettyXml

Continue reading →

Gradle Goodness: Task Output Annotations Create Directory Automatically

Posted on by  
Hubert Klein Ikkink

One of the great features of Gradle is incremental build support. With incremental build support a task is only executed if it is really necessary. For example if a task generates files and the files have not changed than Gradle can skip the task. This speeds up the build process, which is good. If we write our own tasks we can use annotations for properties and methods to make them behave correctly for incremental build support. The @OutputDirectory annotation for example can be used for a property or method that defines a directory that is used by the task to put files in. The nice thing is that once we have designated such a directory as the output directory we don't have to write code to create the directory if it doesn't exist. Gradle will automatically create the directory if it doesn't exist yet. If we use the @OutputFile or @OutputFiles annotation the directory part of the file name is created if it doesn't exist.

In the following example build file we create a new task SplitXmlTask with the property destinationDir and we apply the @OutputDirectory annotation. If the directory doesn't exist Gradle will create it when we execute the task.

Continue reading →

Gradle Goodness: Init Script for Adding Extra Plugins to Existing Projects

Posted on by  
Hubert Klein Ikkink

Gradle is very flexible. One of the ways to alter the build configuration is with initialization or init scripts. These are like other Gradle scripts but are executed before the build. We can use different ways to add the init script to a build. For example we can use the command-line option -I or --init-script, place the script in the init.d directory of our GRADLE_HOME directory or USER_HOME/.gradle directory or place a file init.gradle in our USER_HOME/.gradle directory.

We can also use the apply(from:) method to include such a script in our build file. We can reference a file location, but also a URL. Imagine we place an init script on our company intranet to be shared by all developers, then we can include the script with the apply(from:) method. In the following build file we use this syntax to include the script:

Continue reading →

Gradle Goodness: Exclude Transitive Dependency from All Configurations

Posted on by  
Hubert Klein Ikkink

We can exclude transitive dependencies easily from specific configurations. To exclude them from all configurations we can use Groovy's spread-dot operator and invoke the exclude() method on each configuration. We can only define the group, module or both as arguments for the exclude() method.

The following part of a build file shows how we can exclude a dependency from all configurations:

Continue reading →

shadow-left