I have a declarative spring config
@Configuration
public class SpringConfig {
@Bean
public someBean() {
return new Bean1();
}
}
and a @Component annotated Bean
@Component
public class Bean2 {
}
Now I would like to use both of then in my UnitTest
@RunWith(SpringJUnit4ClassRunner.class)
public void UnitTest {
@Autowired Bean1 bean1;
@Autowired Bean2 bean2;
}
but I have no idea how to do it.
You can do this:
@ContextConfiguration(classes = {SpringConfig.class})
@RunWith(SpringJUnit4ClassRunner.class)
public void UnitTest {
@Autowired Bean1 bean1;
@Autowired Bean2 bean2;
}
For class Bean2, you can add the @ComponentScan annotation:
@Configuration
@ComponentScan("com....package.of.bean2")
public class SpringConfig {
@Bean
public someBean() {
return new Bean1();
}
}
If you don't want to add the ComponentScan to your SpringConfig class, you can add an additional test config class with the ComponentScan annotation and add it to the ContextConfiguration annotation:
@ContextConfiguration(classes = {SpringConfig.class, SpringTestConfig.class})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.