1

In product code, I can use the following code to read the aws.default.region property from application.properties and application-development.properties

@Value("${aws.default.region:null}")
private String awsDefaultRegion;

However, in unit test the same code doesn't work, and awsDefaultRegion variable is always null.

I tried to add the following annotation but it doesn't work.

@PropertySource({
        "classpath:application.properties",
        "classpath:application-development.properties"
})
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
powerseed
  • 1,090
  • 3
  • 17
  • 29
  • @SergeyVyacheslavovichBrunov I am afraid `TestPropertySource` doesn't work either – powerseed Jan 28 '22 at 15:16
  • Could you please provide a minimal reproducible example? Please, see: [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). – Sergey Vyacheslavovich Brunov Jan 28 '22 at 15:20
  • There is too little information in here. An `@Value` (like `@Autowired`) cannot be `null`. If it is `null` it is because it isn't Spring that is creating an instance but yourself. So you are probably doing `new YourObject()` in your test (or using a Mock) at least something outside the control of Spring. All of this is something we cannot see because you haven't included your actual test class. – M. Deinum Jan 28 '22 at 17:46

2 Answers2

0

If you use JUnit:

@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource("classpath:test-application.properties")
Steve H.
  • 6,912
  • 2
  • 30
  • 49
0

I think inject value on test could be another good way


ReflectionTestUtils.setField(
   serviceMocked, 
  "awsDefaultRegion",  // name attr in service
   valueaTobeInjectWhenTesting
);

// rest of test method

Dilermando Lima
  • 1,004
  • 8
  • 21