Ask Your Question
4

How can we remove unnecessary `AutoConfigureEmbeddedDatabase` from spring tests and load only essential context for the test?

asked 2021-11-19 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-04-14 18:00:00 +0000

huitzilopochtli gravatar image

There are a few ways to remove unnecessary AutoConfigureEmbeddedDatabase from Spring tests and load only the essential context for the test:

  1. Use the @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;

    // ...
}
  1. If you are using Spring Boot, you can use the @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;

    // ...
}
  1. If you only need to test a specific component, you can use the @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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-11-19 11:00:00 +0000

Seen: 20 times

Last updated: Apr 14 '21