Quantcast
Channel: Java Creed » Spring
Viewing all articles
Browse latest Browse all 8

How to mock the @Value properties during tests

$
0
0

Spring allows you to provide an instance of PropertySourcesPlaceholderConfigurer which will be used to populate the values of the fields annotated with @Value().

/**
 * Creates the mock properties that will be used for this test. 
 * These will be used mainly to populate the {@code @Value("")} fields.
 * 
 * @return the mock properties source place holders configure
 */
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
  final PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
  /* 
   * Instead of loading the properties from the file system, the test makes use of the following 
   * hard-coded properties 
   * pspc.setLocation(new ClassPathResource("project.properties"));
   */
  final Properties properties = new Properties();
  properties.setProperty("property.value1", "value1");
  properties.setProperty("property.value2", "value2");
  properties.setProperty("property.valueN", "valueN");
  pspc.setProperties(properties);
  return pspc;
}

Viewing all articles
Browse latest Browse all 8

Trending Articles