1 | initial version |
There are a few ways to remove unnecessary AutoConfigureEmbeddedDatabase
from Spring tests and load only the essential context for the test:
@ContextConfiguration
annotation to specify which configuration classes or XML files to load for the test. This allows you to explicitly load only the necessary beans and avoid unnecessary auto-configuration:@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {TestConfig.class, ServiceUnderTest.class})
public class MyTest {
@Autowired
private ServiceUnderTest service;
// ...
}
@SpringBootTest
annotation with the classes
attribute to specify which configuration classes to load. This approach loads the entire application context, but only with the necessary configuration classes:@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfig.class)
public class MyTest {
@Autowired
private ServiceUnderTest service;
// ...
}
@WebMvcTest
or @DataJpaTest
annotations, which load only the necessary parts of the application context for testing specific components:@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
public class MyControllerTest {
@Autowired
private MockMvc mockMvc;
// ...
}
Overall, the key is to be intentional and explicit about what parts of the application context you are loading for each test, rather than relying on auto-configuration defaults. This will help you minimize test setup time and avoid potential conflicts or inconsistencies caused by unnecessary beans.