I was able to set up and successfully run three different test configurations with SpringBoot 1.5.3
Method #1. Importing Bean with use of @Import annotation
@RunWith(SpringJUnit4ClassRunner.class)
@Import({MyBean.class})
public class MyBeanTest() {
@Autowired
private MyBean myBean;
}
Method #2. Importing Bean with use of @ContextConfiguration annotation
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MyBean.class})
public class MyBeanTest() {
@Autowired
private MyBean myBean;
}
Method #3 (with internal class configuration; based on the official blog post)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class MyBeanTest() {
@Configuration
static class ContextConfiguration {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
@Autowired
private MyBean myBean;
}
Taking into account @Import annotation documentation
Indicates one or more {@link Configuration @Configuration} classes to import.
and the fact that MyBean is not a configuration class, but a bean class annotated with @Component annotation it looks like Method #1 is not correct.
From @ContextConfiguration documentation
{@code @ContextConfiguration} defines class-level metadata that is used to determine how to load and configure an {@link org.springframework.context.ApplicationContext ApplicationContext} for integration tests.
Sounds like it is better applicable to unit tests, but still, should load a kind of a configuration.
Methods #1 and #2 are shorter and simpler. Method #3 looks like a correct way.
Am I right? Are there other criteria why I should use method #3, like performance or something else?