I have a code similar to the follows:
@RunWith(SpringRunner.class)
@SpringBootTest
public class ModelRunnerTest {
@Autowired
private SomeRepository repository;
@Autowired
private SomeSearcher someSearcher;
@Test
public void test(){
someSearcher.search(repository);
}
}
It works - but also create all beans in the same context as the 2 created beans. This can take a long time (and I run this test every build/deploy).
So, I would like to find a way for the test to load only the necessary beans for the test. In this example it will be only repository & someSearcher.
I know I can provide an alternative implementation for beans using @BeanMock, but the actual implementations for the beans will still be created (although not used).
Any suggestions?
You could use @ContextConfiguration
instead of @SpringBootTest
to create a custom Spring context for particular classes. Spring Boot further simplifies this with classes designed for particular use-cases e.g. @WebMvcTest
or @DataJdbcTest
.
This approach however has two main drawbacks:
What are you actually testing with this new limited context? Definitely not the production application since you are not starting the whole Spring context. This can lead to bugs being missed by the tests e.g. bean overriding problems might not be spotted.
SpringRunner
will attempt to reuse the Spring context between the tests if possible. Starting one big context once and sharing it across all the tests might be faster when you have multiple tests.