4

[Spring Boot, Spock] Disable components for SpringBootTest tests by replacing th...

 1 year ago
source link: https://gist.github.com/msievers/9b884af60e3c159251095019d2f5a60c
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
[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.

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK