Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save msievers/9b884af60e3c159251095019d2f5a60c to your computer and use it in GitHub Desktop.
Save msievers/9b884af60e3c159251095019d2f5a60c to your computer and use it in GitHub Desktop.
[Spring Boot, Spock] Disable components for SpringBootTest tests by replacing them with mocks

Motivation

Annotating a test with @SpringBootTest will usally lead to initializing a Spring context with all components found by Springs component scan mechanism (usally all components of your app). Sometimes, you want some components to be excluded from component scan within your tests, for example

  • startup event listeners
  • setup code which configures external systems/apis/clients etc.
  • ...

Sadly, there is only a whitelist mechanism imposed by @SpringBootTest(classes = ...) which will only load the listed classes into the tests Spring context. If you have many classes and just want to exclude some of them, this can be complex and tedious.

Idea

Lets @SpringBootTest do its job, without specifying classes = ..., but replace the components, you would like to be removed from the context by (empty) mocks. This will effectivly disable the behaviour imposed by these components.

Example

The following utilizes Spock 1.2, which brings a neat new annotation/feature @SpringBean which makes it super easy to provide mocks for certain beans.

import com.github.msievers.app.ApplicationStartupListener
import com.github.msievers.app.EventConfiguration

import org.spockframework.spring.SpringBean
import org.springframework.boot.test.context.SpringBootTest
import spock.lang.Specification

@SpringBootTest
class SomeSpec extends Specification {

    // Mock things that make context initializing hard/impossible
    @SpringBean ApplicationStartupListener applicationStartupListener = Mock(ApplicationStartupListener)
    @SpringBean EventConfiguration eventConfiguration = Mock(EventConfiguration)

    def "someTest"() {
        setup:
        // ...
    }
}

Resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment