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.
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:
// ...
}
}