Pregunta

So, I'm working on some Spring tests which require dependency injection using annotations:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class BeanTest {

  @Autowired
  private SomeService someService;

  @Configuration
  static class ContextConfiguration {
    @Bean
    public SomeService someService() {
        return new SomeService();
    }
  }
}

I'd really like to not have to repeat this code in every test but my attempts to create a base class which contains the configuration:

@Configuration
class MyContextConfiguration {
   @Bean
   public SomeService someService() {
       return new SomeService();
   }
}

And deriving from it:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class BeanTest {

  @Autowired
  private SomeService someService;

  @Configuration
  static class ContextConfiguration extends MyContextConfiguration {}
}

Don't seem to work. Can anybody suggest a way to DRY this up?

Thanks!

¿Fue útil?

Solución

You should be able to do this instead.

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

  @Autowired
  private SomeService someService;

  @Configuration
  @Import(MyContextConfiguration.class)
  static class ContextConfiguration {
  ....
  }
}

Also, you don't need to mention AnnotationConfigContextLoader, Spring by convention will automatically pick up the static inner class annotated with @Configuration and use the appropriate ContextLoader

Otros consejos

You can declare configuration classes in the the contextconfiguration-annotation. From the documentation.

ContextConfiguration Defines class-level metadata that is used to determine how to load and configure an ApplicationContext for integration tests. Specifically, @ContextConfiguration declares the application context resource locations or the annotated classes that will be used to load the context. Resource locations are typically XML configuration files located in the classpath; whereas, annotated classes are typically @Configuration classes. However, resource locations can also refer to files in the file system, and annotated classes can be component classes, etc.

example from the documentation.

@ContextConfiguration(classes = TestConfig.class)
public class ConfigClassApplicationContextTests {
    // class body...
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top