Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Spring Rest Controller Testing

farenda 2015-06-06 0

Problem:

How to test Spring Rest Controller?

Solution:

Sample Gradle build script to run test:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.3.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'groovy'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
    baseName = 'spring-rest-controller-testing'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    // mandatory dependencies for using Spock
    compile "org.codehaus.groovy:groovy-all:2.4.1"
    testCompile "org.spockframework:spock-core:1.0-groovy-2.4"

    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework.plugin:spring-plugin-core:1.1.0.RELEASE")
    testCompile("org.springframework.boot:spring-boot-starter-test")
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.4'
}

Domain object that will be converted to JSON when returned from REST Controller:

package com.farenda.solved;

public class User {

    private final Long id;
    private final String name;

    public User(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}

A Repository/DAO/Service that will provide domain objects for our REST controller:

package com.farenda.solved;

import java.util.List;

// An interface is enough as we don't want to test its logic.
public interface UserRepository {
    List<User> getAll();
}

REST Controller that we want to test:

package com.farenda.solved;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

@RestController
public class JavaSolvedController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping(method = GET, value = "/user",
                    produces = APPLICATION_JSON_VALUE)
    @ResponseStatus(HttpStatus.OK)
    public List<User> listUsers() {
        return userRepository.getAll();
    }
}

Finally Spock test using Spring MVC Test, which is part of spring-test since Spring 3.2:

package com.farenda.solved

import org.springframework.http.MediaType
import org.springframework.test.web.servlet.setup.MockMvcBuilders
import spock.lang.Specification
import spock.lang.Subject

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*

// No @ContextConfiguration with Spring MVC Test!
class JavaSolvedControllerTest extends Specification {

    // Don't want to call real service, so use mock
    def repository = Mock(UserRepository)
    // Init controller with mock:
    def @Subject api = new JavaSolvedController(userRepository: repository)

    // Let Spring MVC Test process the controller:
    def mockMvc = MockMvcBuilders.standaloneSetup(api).build()

    def 'should call rest controller'() {
        when:
        // Try different URL or Method to see what will happen!
        def result = mockMvc.perform(get('/user'))

        then:
        // Expect 1 call to repository to get users:
        1 * repository.getAll() >> [new User(1, 'franek')]
        result.andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(content().string('[{"id":1,"name":"franek"}]'))
    }
}

Nice thing is that we don’t have to create whole Spring Application Context just to test simple Rest Controller. Spring MVC Test will process controller’s annotations and allow to easily test every its aspect!

Share with the World!
Categories Spring Framework Tags java, rest, spring
Previous: Java Literals
Next: Java Switch Case

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok