Archive: March 2015

Nifty JUnit : Working with temporary files

Posted on by  
Willem Cheizoo

I get this question quite often and I struggled with it many times before: How do I work with temporary files in my JUnit testcases? I would like to explain two simple ways of working with temporary files in JUnit.

Create a temporary file with the Java File API and mark it directly as deleteOnExit(). The created file will be deleted when the JVM exits.

Continue reading →

Integration testing on REST urls with Spring Boot

Posted on by  
Ties van de Ven

We are building a Spring Boot application with a REST interface and at some point we wanted to test our REST interface, and if possible, integrate this testing with our regular unit tests. One way of doing this, would be to @Autowire our REST controllers and call our endpoints using that. However, this won't give full converage, since it will skip things like JSON deserialisation and global exception handling. So the ideal situation for us would be to start our application when the unit test start, and close it again, after the last unit test. It just so happens that Spring Boot does this all for us with one annotation: @IntegrationTest. Here is an example implementation of an abstract class you can use for your unit-tests which will automatically start the application prior to starting your unit tests, caching it, and close it again at the end.

package demo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.fasterxml.jackson.databind.ObjectMapper;

@RunWith(SpringJUnit4ClassRunner.class)
// Your spring configuration class containing the @EnableAutoConfiguration
// annotation
@SpringApplicationConfiguration(classes = Application.class)
// Makes sure the application starts at a random free port, caches it throughout
// all unit tests, and closes it again at the end.
@IntegrationTest("server.port:0")
@WebAppConfiguration
public abstract class AbstractIntegrationTest {

    // Will contain the random free port number
    @Value("${local.server.port}")
    private int port;

    /**
     * Returns the base url for your rest interface
     *
     * @return
     */
    private String getBaseUrl() {
        return "http://localhost:" + port;
    }

    // Some convenience methods to help you interact with your rest interface

    /**
     * @param requestMappingUrl
     *            should be exactly the same as defined in your RequestMapping
     *            value attribute (including the parameters in {})
     *            RequestMapping(value = yourRestUrl)
     * @param serviceReturnTypeClass
     *            should be the the return type of the service
     * @param parametersInOrderOfAppearance
     *            should be the parameters of the requestMappingUrl ({}) in
     *            order of appearance
     * @return the result of the service, or null on error
     */
    protected T getEntity(final String requestMappingUrl, final Class serviceReturnTypeClass, final Object... parametersInOrderOfAppearance) {
        // Make a rest template do do the service call
        final TestRestTemplate restTemplate = new TestRestTemplate();
        // Add correct headers, none for this example
        final HttpEntity requestEntity = new HttpEntity(new HttpHeaders());
        try {
            // Do a call the the url
            final ResponseEntity entity = restTemplate.exchange(getBaseUrl() + requestMappingUrl, HttpMethod.GET, requestEntity, serviceReturnTypeClass,
                    parametersInOrderOfAppearance);
            // Return result
            return entity.getBody();
        } catch (final Exception ex) {
            // Handle exceptions
        }
        return null;
    }

    /**
     * @param requestMappingUrl
     *            should be exactly the same as defined in your RequestMapping
     *            value attribute (including the parameters in {})
     *            RequestMapping(value = yourRestUrl)
     * @param serviceListReturnTypeClass
     *            should be the the generic type of the list the service
     *            returns, eg: List * @param parametersInOrderOfAppearance
     *            should be the parameters of the requestMappingUrl ({}) in
     *            order of appearance
     * @return the result of the service, or null on error
     */
    protected List getList(final String requestMappingUrl, final Class serviceListReturnTypeClass, final Object... parametersInOrderOfAppearance) {
        final ObjectMapper mapper = new ObjectMapper();
        final TestRestTemplate restTemplate = new TestRestTemplate();
        final HttpEntity requestEntity = new HttpEntity(new HttpHeaders());
        try {
            // Retrieve list
            final ResponseEntity entity = restTemplate.exchange(getBaseUrl() + requestMappingUrl, HttpMethod.GET, requestEntity, List.class, parametersInOrderOfAppearance);
            final List> entries = entity.getBody();
            final List returnList = new ArrayList();
            for (final Map entry : entries) {
                // Fill return list with converted objects
                returnList.add(mapper.convertValue(entry, serviceListReturnTypeClass));
            }
            return returnList;
        } catch (final Exception ex) {
            // Handle exceptions
        }
        return null;
    }

    /**
     *
     * @param requestMappingUrl
     *            should be exactly the same as defined in your RequestMapping
     *            value attribute (including the parameters in {})
     *            RequestMapping(value = yourRestUrl)
     * @param serviceReturnTypeClass
     *            should be the the return type of the service
     * @param objectToPost
     *            Object that will be posted to the url
     * @return
     */
    protected T postEntity(final String requestMappingUrl, final Class serviceReturnTypeClass, final Object objectToPost) {
        final TestRestTemplate restTemplate = new TestRestTemplate();
        final ObjectMapper mapper = new ObjectMapper();
        try {
            final HttpEntity requestEntity = new HttpEntity(mapper.writeValueAsString(objectToPost));
            final ResponseEntity entity = restTemplate.postForEntity(getBaseUrl() + requestMappingUrl, requestEntity, serviceReturnTypeClass);
            return entity.getBody();
        } catch (final Exception ex) {
            // Handle exceptions
        }
        return null;
    }
}

Continue reading →

Building Vert.x projects using Gradle

Posted on by  
Rob Brinkman

We currently use Vert.x in several internal and external projects. Until the most recent project we where building our Vert.x modules using Maven. Gradle is our build tool of choice, but the default approach described at the Vert.x site caused several issues:

  • The task of cloning, cleaning and configuring the template project is error-prone;
  • The template project does not support recent Gradle versions >= 2.x;
  • This approach is not compatible with the Gradle support in IntelliJ IDEA.

Continue reading →

Prevent 'No plugin found' in multi-module maven

Posted on by  
Willem Cheizoo

Defining a maven plugin on a submodule in a multi-module maven project can give us a 'No plugin found' error. Especially if we have a multi-module project and we want to apply a maven plugin in only one specific module this error occur pretty often. Let's say we have a multi-module root pom which looks like this.

 4.0.0

  com.jdriven.blog
  maven-plugin-multimodule
  0.1-SNAPSHOT
  pom

  module1 
    module2 

Continue reading →

Gradle Goodness: Define System Properties in gradle.properties File

Posted on by  
Hubert Klein Ikkink

To define system properties for our Gradle build we can use the command line option --system-prop or -D. But we can also add the values for system properties in the gradle.properties file of our project. This file contains project properties we want to externalized, but if we prefix the property name with systemProp. the property is turned into a system property. For a multi-module build only system properties defined in the gradle.properties file in the root of the project structure are used, others are ignored.

In the following build script we have the task showSystemProperty. Inside the task we assert the value of the system property sample and the project property sample:

Continue reading →

Awesome Asciidoctor: Use Inline Extension DSL with Gradle

Posted on by  
Hubert Klein Ikkink

One of the great features of Asciidoctor is the support for extensions. If we want to have some special feature we want to use, but is not supported by Asciidoctor, we can add our own extension. On the Java platform we can write those extensions in for example Java and Groovy. When we use Gradle as the build tool with the Asciidoctor plugin we can write the code for the extension in our Gradle build file with the Groovy extension DSL.

Suppose we want to write a new inline macro that will transform the following markup issue:PRJ-100[] into a link that points to the web page for issue PRJ-100. First we create our Asciidoctor source document:

Continue reading →

Akka and scalatest in gradle

Posted on by  
Tammo Sminia

When you start using Scala, it's tempting to also start using sbt. You can also use your favorite build tool: Gradle. This is my default Gradle build file:

apply plugin: 'scala'

repositories {
  mavenCentral()
}

dependencies {
  compile group: 'org.scala-lang', name: 'scala-library', version: '2.11.5'
  compile group: 'com.typesafe.akka', name: 'akka-actor_2.11', version: '2.3.9'
  compile group: 'com.typesafe.akka', name: 'akka-remote_2.11', version: '2.3.9'
  testCompile group: 'org.scalatest', name: 'scalatest_2.11', version: '2.2.4'
}

//run the akka application
task run(type: JavaExec, dependsOn: classes) {
  //object to run. (The one that extends App)
  main = 'pi.Pi'
  classpath sourceSets.main.runtimeClasspath
  classpath configurations.runtime
}

//run scala tests. These are not automatically picked up by gradle,
//so we run them like this.
task spec(dependsOn: ['testClasses'], type: JavaExec) {
  main = 'org.scalatest.tools.Runner'
  args = ['-R', 'build/classes/test', '-o']
  classpath = sourceSets.test.runtimeClasspath
}

Continue reading →

Awesome Asciidoctor: Creating a Checklist

Posted on by  
Hubert Klein Ikkink

Creating a list with Asciidoctor markup is easy. To create an unordered we need to start a line with an asterisk (*) or hypen (-). We can add some extra markup to create a checked list. If we add two square brackets ([]) to the list item we have a checklist. To have an unchecked item we use a space, for a checked item we can use a lowercase x (x) or an asterisk (*).

In the next example we define a shopping cart list with Asciidoctor markup:

Continue reading →

Awesome Asciidoctor: Change Start Number for Numbered List

Posted on by  
Hubert Klein Ikkink

With Asciidoctor we can create numbered lists easily. When we want to change the number the list starts with we use the start attribute when we define the list.

== Numbered List

.Default
. Makes writing easy
.. Keep focus
.. Syntax
. Different output formats

// Start this list from 10.
[start=10]
.Start from 10
. Makes writing easy
// We can use it on all levels.
[start=10]
.. Keep focus
.. Syntax
. Different output formats

Continue reading →

Awesome Asciidoctor: Customize How Missing Attributes Are Handled

Posted on by  
Hubert Klein Ikkink

Document attributes are like variables for your Asciidoctor document. Normally when we reference an attribute that is not set in our Asciidoctor markup the reference is still in the output. This is very handy, because we immediately see that a document attribute is not set. But we can customize this behavior with the document attribute attribute-missing. We can use the default value skip, which leaves the reference in the output. Another option is drop, which means the reference is dropped from the output. Finally we can set the value to drop-line, where the complete line with the attribute reference is dropped from the output.

In the following sample Asciidoctor markup we set the three values for the attribute attribute-missing:

Continue reading →

shadow-left