How to mock the @Value properties during tests

5 years ago by in How To, Spring Tagged: , , ,

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
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(""));
  final Properties properties = new Properties();
  properties.setProperty("property.value1", "value1");
  properties.setProperty("property.value2", "value2");
  properties.setProperty("property.valueN", "valueN");
  return pspc;
Albert Attard

Albert Attard is a Java passionate and technical lead at a research group. You can find him on . Over the past years Albert worked on various Java projects including traditional server/client applications, modular applications, large data handling applications and concurrent data manipulation applications to name a few. He has a BSc degree from the University of London (Homepage) and an MSc Information Security with the same university. His MSc thesis (Book) received the 2012 award (Website).

Leave a Comment

Time limit is exhausted. Please reload the CAPTCHA.