title: Injecting Configuration object to a service bean during Unit test in Spring Boot
body: <p><strong>Problem Summary:</strong></p>
  
  <p>A configuration object is created successfully during regular run (using <code>@Autowired</code>), but is <code>null</code> when running in unit test phase.</p>
  
  <p><strong>Edit, in response to flagging the question as duplicate:</strong> 
  I don't think this is a duplication of <a href="https://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null">Why is my Spring @Autowired field null?</a> as my question is about unit test phase and the above question is about regular run phase.</p>
  
  <p><strong>Detailed:</strong></p>
  
  <p>I have a configuration object that reads a properties file:</p>
  
  <pre><code>@Configuration
  @ConfigurationProperties(prefix = "defaults")
  @Getter
  @Setter
  public class DefaultsConfigProperties {
     Double value;
     ....
  </code></pre>
  
  <p>In the service layer, I'm using this class successfully when running the app in regular mode:</p>
  
  <pre><code>@Service
  @Configuration   
  public class CatsService {
  
  @Autowired
  DefaultsConfigProperties defaultsConfigProperties;
  ...
  </code></pre>
  
  <p>However, <strong>the problem is during Unit test</strong>, as the <code>defaultsConfigProperties</code> is <code>null</code>.</p>
  
  <p>Here is the test class:</p>
  
  <pre><code>@RunWith(SpringJUnit4ClassRunner.class)
  @SpringBootTest
  @TestPropertySource(properties = {
      "defaults.value=0.2"
  })
  public class CatServiceTest {
  private CatService;
  
  @Before
  public void before(){
      catService = new CatService();
  }
  </code></pre>
  
  <p>If I understand correctly, I need to somehow create / inject / mock the <code>DefaultsConfigProperties</code> class during the unit test phase.</p>
  
  <p>I also know that using the <code>@Autowired</code> is not recommended and it is better to pass items to the constructor of the class.
  So, should the solution be that the <code>CatService</code> will need to accept the <code>DefaultsConfigProperties</code> in the constructor, and then to create it (how?) in the <code>CatServiceTest</code> ?</p>