Skip to content

Latest commit

 

History

History
47 lines (32 loc) · 2.23 KB

File metadata and controls

47 lines (32 loc) · 2.23 KB

Testing

Spring Boot includes a number of testing utilities and support classes as well as a dedicated starter that provides common test dependencies. This section answers common questions about testing.

Testing With Spring Security

Spring Security provides support for running tests as a specific user. For example, the test in the snippet below will run with an authenticated user that has the ADMIN role.

link:{docs-java}/howto/testing/withspringsecurity/MySecurityTests.java[role=include]

Spring Security provides comprehensive integration with Spring MVC Test and this can also be used when testing controllers using the @WebMvcTest slice and MockMvc.

For additional details on Spring Security’s testing support, see Spring Security’s {spring-security-docs}/servlet/test/index.html[reference documentation].

Use Testcontainers for Integration Testing

The Testcontainers library provides a way to manage services running inside Docker containers. It integrates with JUnit, allowing you to write a test class that can start up a container before any of the tests run. Testcontainers is especially useful for writing integration tests that talk to a real backend service such as MySQL, MongoDB, Cassandra and others. Testcontainers can be used in a Spring Boot test as follows:

link:{docs-java}/howto/testing/testcontainers/vanilla/MyIntegrationTests.java[role=include]

This will start up a docker container running Neo4j (if Docker is running locally) before any of the tests are run. In most cases, you will need to configure the application using details from the running container, such as container IP or port.

This can be done with a static @DynamicPropertySource method that allows adding dynamic property values to the Spring Environment.

link:{docs-java}/howto/testing/testcontainers/dynamicproperties/MyIntegrationTests.java[role=include]

The above configuration allows Neo4j-related beans in the application to communicate with Neo4j running inside the Testcontainers-managed Docker container.