HomeAboutArchivesTools & ResourcesSupport me
Hi! 👋 I'm Szymon

I help you become a better software developer.

  • 1.15kFollowers
  • 2.36kSubscribers
  • 110Followers
  • 30.2kReputation

Latest posts from the Ratpack Cookbook

Using the same prefix with different HTTP methods in Ratpack
Ratpack on GraalVM - how to start?
Ratpack: register SessionModule in handler unit test
Ratpack: mocking Session object in GroovyRequestFixture test
More

Popular categories

  • Groovy Cookbook28
  • Jenkins Pipeline Cookbook9
  • Programmer's Bookshelf6
  • Micronaut Cookbook4
  • Ratpack Cookbook4
  • Learning Java4
  • jq cookbook3
  • How to3
  • Blog Reports2

Don't miss anything - join my newsletter

Additional materials and updates for subscribers. No spam guaranteed.
Unsubscribe at any time.

Did you like this article?

Spread the !
  • ☕️
  1. e.printstacktrace.blog
  2. Ratpack Cookbook

Ratpack: mocking Session object in GroovyRequestFixture test

  • June 24, 2018
  • 2 min. read
  • 0 Comments

Ratpack allows you unit test handlers using GroovyRequestFixture class. The good thing about this approach is that it does not require running the whole application and you can quickly test if the handler does what you expect. However, if you retrieve objects from Raptack’s registry you will run into a problem - registry in this case is empty.

In some cases you may find mocking Session object useful. Especially if you only want to retrieve specific object or value from session and do something with it. GroovyRequestFixture.handle(chain, closure) gives you an access to registry through the closure passed in the second parameter.

GroovyRequestFixture.handle(yourHandler) {
    registry { r ->
        r.add(Session, mockSession)
    }
}

Here we have registered mockSession to be injected anytime Session instance is being retrieved from the registry. Keep in mind that mock object does nothing by default (e.g. it return null values for methods invocation) so you will have to "configure" your mock object to return something significant. For instance:

Session mockSession = Mock(Session) {
    get('test') >> Promise.value(Optional.of('Lorem ipsum'))
}

will return Lorem ipsum value (as a promise of optional) for session.get('test').

And here you can find a full example:

import groovy.transform.CompileStatic
import ratpack.exec.Promise
import ratpack.groovy.handling.GroovyChainAction
import ratpack.groovy.test.handling.GroovyRequestFixture
import ratpack.http.Status
import ratpack.jackson.internal.DefaultJsonRender
import ratpack.session.Session
import spock.lang.Specification

import static ratpack.jackson.Jackson.json

class MockSessionSpec extends Specification {

    final Session session = Mock(Session) {
        get('test') >> Promise.value(Optional.of('Lorem ipsum'))
    }

    final GroovyChainAction chainAction = new GroovyChainAction() {
        @Override
        @CompileStatic
        void execute() throws Exception {
            get('foo') {
                get(Session).get('test').map { Optional<String> o ->
                    o.orElse(null)
                }.flatMap { value ->
                    Promise.value(value)
                }.then {
                    render(json([message: it]))
                }
            }
        }
    }

    def "should retrieve message from Session object"() {
        given:
        def result = GroovyRequestFixture.handle(chainAction) {
            uri 'foo'
            method 'GET'
            registry { r ->
                r.add(Session, session)
            }
        }

        expect:
        result.status == Status.OK

        and:
        result.rendered(DefaultJsonRender).object == [message: 'Lorem ipsum']
    }
}
  • groovy
  • ratpack
  • spock
  • unit-test
  • session
  • mock

Ratpack Cookbook

Ratpack: register SessionModule in handler unit test

  • June 26, 2018
  • 2 min. read
  • 0 Comments

Unit testing Ratpack handlers has many benefits. In the previous post we have learned how to mock Session object to use it with GroovyRequestFixture. Today instead of mocking we will register SessionModule and then we will use a real session object.

Ratpack Cookbook

Ratpack: register SessionModule in handler unit test

  • June 26, 2018
  • 2 min. read
  • 0 Comments

Unit testing Ratpack handlers has many benefits. In the previous post we have learned how to moc...

Groovy Cookbook

Spock random order of tests - how to?

  • April 6, 2019
  • 2 min. read
  • 0 Comments

Spock Framework executes test methods (features) in a single class (specification) in the declar...

Groovy Cookbook

How to avoid "No tests were found" when using JUnit 5 with Groovy?

  • October 24, 2018
  • 2 min. read
  • 0 Comments

In this short blog post I would like to explain how to avoid popular mistake when you write your...

Any thoughts or ideas?

Let's talk in the comment's section 💬

Want to put a code sample in the comment? Read the Syntax highlighting guide for more information.
Empty
Latest blog posts
  • Merging JSON files recursively in the command-line
  • Jenkins Declarative Pipeline with the dynamic agent - how to configure it?
  • Groovy Ecosystem Usage Report (2020)
  • How to convert JSON to CSV from the command-line?
  • 5 Common Jenkins Pipeline Mistakes
  • How to merge two maps in Groovy?
  • Building stackoverflow-cli with Java 11, Micronaut, Picocli, and GraalVM
  • How to catch curl response in Jenkins Pipeline?
  • Atomic Habits - book review
  • Parsing JSON in command-line with jq: basic filters and functions (part 1)
Trending videos
Jenkins Declarative Pipeline vs Scripted Pipeline - 4 key differences | #jenkinspipeline

Jenkins Pipeline as a code is a new standard for defining continuous integration and delivery pipelines in Jenkins. The scrip...

5 Common Jenkins Pipeline Mistakes 🔥

In this Jenkins Pipeline tutorial video, I reveal five common Jenkins Pipeline mistakes and I explain how those mistakes can ...

Useful links
  • Start here
  • About
  • Archives
  • Resources
  • Privacy Policy
  • Merchandise
  • My Kit
  • RSS
  • Support the blog
Popular categories
  • Groovy Cookbook28
  • Jenkins Pipeline Cookbook9
  • Programmer's Bookshelf6
  • Micronaut Cookbook4
  • Ratpack Cookbook4
  • Learning Java4
  • jq cookbook3
  • How to3
  • Blog Reports2
Popular tags
affiliate async benchmark blogging book career cicd continuous-integration curl devops docker git github graalvm gradle grails groovy haskell hexo java java-8 jenkins jenkins-pipeline jenkinsfile jmh jq json junit learning maven metaprogramming micronaut native-image non-blocking progress ratpack reactive-programming reading recursion review rxjava sdkman session split spock stackoverflow string tail-call tail-recursion unit-test
  • Designed by @wololock
  • Created with Hexo
  • Hosted on GitHub
  • Deployed with Circle CI
  • License CC BY-NC-SA 4.0