Spring Testing: How to enable auto-scan of beans

烈酒焚心 提交于 2020-02-20 06:41:05

问题


For example, now in each test class I have to do

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)

I want to get rid of

 @ContextConfiguration(loader=AnnotationConfigContextLoader.class)

and want Spring to scan all the beans in my project.

How can I do that?


回答1:


If you have your spring configuration in an xml file you would use something like:

@ContextConfiguration(locations="classpath:applicationContext.xml")

If you use Java Config then you would use

@ContextConfiguration(classes=Config.class)

I used generic names in the above samples, you'll of course need to adapt to your project's configuration.

In both cases Spring's component scanning will need to be enabled for Spring to pickup the annotated classes.




回答2:


You can do this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MyTest {

  @Test
  public void testSomething() {

  }

  @Configuration
  @ComponentScan("basepackage")
  public static class SpringConfig {

  }
}

By default @ContextConfiguration will look for static inner classes annotated with @Configuration, which is why this set up will just work.

You can get rid of loader param altogether, that is not required




回答3:


You can also simply add @SpringBootTest if using Spring Boot.



来源:https://stackoverflow.com/questions/23416366/spring-testing-how-to-enable-auto-scan-of-beans

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!