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