Please enable JavaScript.
Coggle requires JavaScript to display documents.
Spring Tests - Coggle Diagram
Spring Tests
The SpringBootTest annotation is useful when we need to bootstrap the entire container. The annotation works by creating the ApplicationContext that will be utilized in our tests. It starts the embedded server, creates a web environment, and then enables Test methods to do integration testing.
params
webEnvironment
We can use the webEnvironment attribute of SpringBootTest to configure our runtime environment; we’re using WebEnvironment.MOCK here so that the container will operate in a mock servlet environment.
is an alternative to SpringRunner and works with JUnit5. It’s also used to run integration tests and load Spring TestContext.
wbe env
By default, SpringBootTest does not start a server. We need to add the attribute webEnvironment to further refine how your tests run. It has several options:
NONE: Loads an ApplicationContext by using SpringApplication but does not provide any web environment.
-
RANDOM_PORT: Loads a WebServerApplicationContext and provides a real web environment. The embedded server is started and listened to a random port. This is the one that should be used for the integration test.
-
properties
Please note that methods annotated with DynamicPropertySource must be declared as static and must accept only one argument of type DynamicPropertyRegistry.
Basically, the main motivation behind the DynmicPropertySource annotation is to more easily facilitate something that was already possible. Although it was initially designed to work with Testcontainers, it's possible to use it wherever we need to work with dynamic configurations.
-
helps configure the locations of properties files specific to our tests. Note that the property file loaded with TestPropertySource will override the existing application.properties file.
is a Spring testing annotation. It indicates the associated test or class modifies the ApplicationContext. It tells the testing framework to close and recreate the context for later tests.
We can annotate a test method or an entire class. By setting the MethodMode or ClassMode, we can control when Spring marks the context for closure.
Configuration classes annotated with TestConfiguration are excluded from component scanning, therefore we need to import it explicitly in every test where we want to Autowire it. We can do that with the Import annotation:
s an alias for the class SpringJUnit4ClassRunner and works with JUnit4-based test classes. It loads Spring TestContext, through which spring beans and configurations become available to use along with JUnit annotations. We’ll require JUnit 4.12 or higher to use this.