Speeding up Test Execution, Spring Context Mocking
Overview
Writing test code in every project has become a common practice. As projects grow, the number of tests inevitably increases, leading to longer overall test execution times. Particularly in projects based on the Spring framework, test execution can significantly slow down due to the loading of Spring Bean contexts. This article introduces methods to address this issue.
Write All Tests as Unit Tests
Tests need to be fast. The faster they are, the more frequently they can be run without hesitation. If running all tests once takes 10 minutes, it means feedback will only come after 10 minutes.
To achieve faster tests in Spring, it is essential to avoid using @SpringBootTest
. Loading all Beans causes the time to load necessary Beans to be overwhelmingly longer than executing the code for testing business logic.
@SpringBootTest
class SpringApplicationTest {
@Test
void main() {
}
}
The above code is a basic test code for running a Spring application. All Beans configured by @SpringBootTest
are loaded. How can we inject only the necessary Beans for testing?