Вопрос

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?

Это было полезно?

Решение 2

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.

Другие советы

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

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

    @TestConfiguration 
    @ComponentScan("basepackage")
    public class TestConfig{

    }

Adding a config class lets spring to load application context. This solved this issue for me.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top